关联名称与 Active Record 中的方法冲突

Association name conflicts with method in Active Record

您好,我是 rails 的初学者,正在与各种协会建立 database/model。

我希望我的 transactions 控制器将 transactions 记录和相应的 subtransactions 记录保存到数据库(即交易中每个子交易(例如产品)的一行).

创建新的 table subtransactions(与 transactions 关联)后,出现以下异常:

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.

我对这告诉我的内容有点困惑,或者更具体地说,在哪里寻找错误。不确定如何找出我的关联与哪种方法冲突。

你的问题是因为你的模型名称错误 product_orders table

默认名称应该是

 ProductOrder

如错误消息所述,问题出在您的事务关联上:活动记录对象上已经有一个名为 transaction 的实例方法。

创建一个名为 transaction 的关联还会创建一个同名的 reader 方法,该方法会隐藏先前存在的方法。在过去,当 rails 的某些内部位试图调用方法并最终调用您的关联 reader 方法时,这会导致真正模糊的错误,因此 rails 阻止您这样做。

此外,您不能创建名为 transaction 的新方法,因为 ActiveRecord::Base.transaction 是保留方法。

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