模型上的多个belongs_to导致父项上的accepts_nested_attributes_for出错

时间:2015-02-24 14:55:15

标签: ruby-on-rails ruby activerecord simple-form

我有一个儿童模型belongs_to两个潜在的父模型。其中一个我尝试将accepts_nested_attributes_forsimple_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

我在这里做错了什么,还是我从错误的角度处理问题?

由于

1 个答案:

答案 0 :(得分:1)

正如@vee指出的那样,'transaction'是一个保留字,尽管直到Rails 4.1.x版本才会强制执行。

在应用程序范围内更改“交易”一词需要在客户预算之外完成工作。所以我使用的解决方案是将模块“ActiveRecord :: Associations :: Builder”替换为此处的副本(调整您的Rails版本):

https://github.com/rails/rails/blob/4-1-stable/activerecord/lib/active_record/associations/builder/association.rb

我在我的应用程序(lib / active_record / associations / builder)中的层次结构中的同一位置放置了该association.rb代码的副本,除了以下行注释掉:

# if model.dangerous_attribute_method?(name)
# raise ArgumentError, "You tried to define an association named #{name} on the model #{model.name}, but " \
# "this will conflict with a method #{name} already defined by Active Record. " \
# "Please choose a different association name."
# end

只有当'name'与冲突的术语'transaction'匹配时,你才可以尝试跳过这个(修改'if')。 对于那些被卡住的人来说,这条路线可以防止他们不得不继续使用Rails版本4.0.x或4.1版本的早期版本。