ActiveRecord model name conflicts with with instance method name

532 views
Skip to first unread message

Jason Taylor

unread,
Jul 25, 2018, 1:44:56 AM7/25/18
to Ruby on Rails: Talk
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

Bruno Oliveira

unread,
Jul 25, 2018, 8:38:05 AM7/25/18
to rubyonra...@googlegroups.com
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"

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-ta...@googlegroups.com.
To post to this group, send email to rubyonra...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/e2a741ff-0400-46d6-91be-ca72b682fa51%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Jason Taylor

unread,
Jul 25, 2018, 12:36:34 PM7/25/18
to Ruby on Rails: Talk
Oh wow, even easier an more succinct than I expected the answer to be!  Thanks so much for the feedback.
Reply all
Reply to author
Forward
0 new messages