Matthias
Matthias

Reputation: 1953

Association name conflicts with method in Active Record

Hi I am a beginner with rails and setting up a database/model with various associations.

I want my transactions controller to save to the DB both the transactions record and the corresponding subtransactions records (i.e. one row for each subtransaction (e.g. product) in the transaction).

After creating a new table subtransactions (associated with transactions), I got the following exception:

ArgumentError in TransactionsController#create

You tried to define an association named transaction on the model Subtransaction, 
but this will conflict with a method transaction already defined
by Active Record. Please choose a different association name.

I'm a bit confused about what this tells me, or more specifically where to look for the mistake. Not sure how to find out what method my association is conflicting with.

Upvotes: 2

Views: 2313

Answers (2)

Frederick Cheung
Frederick Cheung

Reputation: 84162

As the error message says, the problem is your transaction association: there is already an instance method on active record objects called transaction.

Creating an association called transaction also creates a reader method of the same name which would shadow the pre-existing method. In the past this would lead to really obscure errors when some internal bit of rails tried to call a method and ended up calling your association reader method instead, so rails stops you doing this.

Also, you cannot create a new method called transaction because ActiveRecord::Base.transaction is a reserved method.

http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html

Upvotes: 6

edikgat
edikgat

Reputation: 869

your problem is because of mistake in name of your model for product_orders table

by default name should be

 ProductOrder

Upvotes: 0

Related Questions