ActiveRecord model name conflicts with with instance method name

Hello all,

I’m currently working on upgrading our application to Rails 4.1 and am running into the following scenario.

We have an existing model named Transaction which conflicts with the ActiveRecord instance method of the same name when we refer to this model in a belongs_to association like this:


class Transaction < ActiveRecord::Base

end

class Thing < ActiveRecord::Base

  belongs_to :transaction

end

This will trigger this error: “You tried to define an association named transaction on the model Thing, but this will conflict with a method transaction already defined by Active Record. Please choose a different association name.”

As far as I can tell, the transaction instance method has existed in ActiveRecord since Rails 3.x but this error was added in 4.1.0.rc1 as shown here: https://github.com/rails/rails/pull/13896

My question is twofold:

  1. Is there a convenient way to rename an association like this without having to change the model name, db table name, etc?

  2. Why is ActiveRecord::Base#transaction available as an instance method in the first place? Seems like this is best implemented as a class method and in fact the instance method version in ActiveRecord just calls the class method version anyway (see here: https://github.com/rails/rails/blob/master/activerecord/lib/active_record/transactions.rb#L299-L302).

The word “Transaction” seems as though it would be a commonly used model name for many Rails applications so I’m just trying to gain an understanding of why this would be taken by ActiveRecord.

Thanks,

Jason

Hi, Jason. You can keep the name. The only difference is that you will have to change the relationship indication.

belongs_to: my_transaction, class_name: “Transaction”, foreign_key: “transaction_id”

Oh wow, even easier an more succinct than I expected the answer to be! Thanks so much for the feedback.