Ruby on rails 未设置外键的ActiveRecord使用.build有许多关联

Ruby on rails 未设置外键的ActiveRecord使用.build有许多关联,ruby-on-rails,validation,activerecord,has-many,Ruby On Rails,Validation,Activerecord,Has Many,我有一个Rails应用程序,具有以下(简化)模型: 与以下内容冲突: collection.build方法返回一个或多个关联类型的新对象。这些对象将从传递的属性实例化,并通过它们的外键创建链接,但关联的对象尚未保存 显然,手动设置成员id是一个简单的解决方法。但我想避免这样。我相信这段代码在以前版本的rails中工作正常;以上是Rails 3.2.3的行为。我在grosser的回答中作为初始值设定项,代码位于: 将其更改为: class ActiveRecord::Reflection::Ass

我有一个Rails应用程序,具有以下(简化)模型:

与以下内容冲突:

collection.build方法返回一个或多个关联类型的新对象。这些对象将从传递的属性实例化,并通过它们的外键创建链接,但关联的对象尚未保存


显然,手动设置成员id是一个简单的解决方法。但我想避免这样。我相信这段代码在以前版本的rails中工作正常;以上是Rails 3.2.3的行为。

我在grosser的回答中作为初始值设定项,代码位于:

将其更改为:

class ActiveRecord::Reflection::AssociationReflection
  def build_association(*options, &block)
    if options.first.is_a?(Hash) and options.first[:type].presence
      options.first[:type].to_s.constantize.new(*options, &block)
    else
      klass.new(*options, &block)
    end
  end
end
解决了这个问题

# member_role.rb
class MemberRole < ActiveRecord::Base
  belongs_to :member, :inverse_of => :member_roles
  validates_presence_of :member_id
end
# Rails console
> m = Member.find(280)
> mr = m.member_roles.build(:role_id => Role.find_by_name("Crew Chief").id)
=> #<MemberRole id: nil, member_id: nil, role_id: 6697350, start_date: nil, \
   end_date: nil, memo: nil, created_at: nil, updated_at: nil>
> mr.save!
ActiveRecord::RecordInvalid: Validation failed: Member can't be blank
> mr.save(:validate => false)
> mr
=> #<MemberRole id: 1834, member_id: nil, role_id: 6697350, start_date: nil, \
   end_date: nil, memo: nil, created_at: "2012-04-11 06:37:00", \
   updated_at: "2012-04-11 06:37:00">
class ActiveRecord::Reflection::AssociationReflection
  def build_association(*options, &block)
    if options.first.is_a?(Hash) and options.first[:type].presence
      options.first[:type].to_s.constantize.new(*options, &block)
    else
      klass.new(*options, &block)
    end
  end
end