【发布时间】:2015-02-24 14:55:15
【问题描述】:
我有一个子模型belongs_to 有两个潜在的父模型。其中之一是我尝试将accepts_nested_attributes_for 与simple_form 一起使用。这样做会给我这个错误:
You tried to define an association named transaction on the model Exchange, but this will conflict with a method transaction already defined by Active Record. Please choose a different association name.
这是我的代码:
交换模型
class Exchange < ActiveRecord::Base
has_one :transaction
accepts_nested_attributes_for :transaction
end
类别模型
class Category < ActiveRecord::Base
has_many :transactions
monetize :budgeted_cents
end
交易模型
class Transaction < ActiveRecord::Base
belongs_to :category, :class_name => 'Category', :primary_key => 'category_id'
belongs_to :exchange, :class_name => 'Exchange', :primary_key => 'exchange_id'
validates :note, presence: true
monetize :amount_cents, with_model_currency: :in_cents_currency
def self.all_currencies(hash)
hash.keys
end
end
我在这里做错了什么还是我从错误的角度解决问题?
谢谢
【问题讨论】:
-
如消息所述,您需要将关联名称更改为
transaction以外的名称。 -
但是,关联的名称 (
transaction) 不是指的是它与 to 关联的模型的名称吗? (即它必须命名为transaction)@vee -
是的,但是
transaction是一个已经在 ActiveRecord 中定义的方法,它是一种保留字。您可以在Exchange模型中执行has_one :tx, class_name: 'Transaction'然后accepts_nested_attributes_for :tx。 -
更多关于 AR
transaction方法:api.rubyonrails.org/classes/ActiveRecord/Transactions/…。 -
我进行了更改,但现在在我的控制器中,当我执行
@exchange.tx = Transaction.new之类的操作时出现错误can't write unknown attribute 'exchange_id'。这是否也与transaction有点保留有关?顺便感谢您的帮助!
标签: ruby-on-rails ruby activerecord simple-form