如何向关联添加其他属性



>我有一个关联:

class ParentChild < ActiveRecord::Base
  attr_accessible :parent_id, child_id, position
  belongs_to class2, :foreign_key => "child_id"
end

class Parent< ActiveRecord::Base
  has_many parent_child
  has_many Parent, through: :parent_child
end

它用于创建父项并关联另一个父项:

Parent.create.parents << Parent.create

但是是否可以设置一个额外的属性,在本例中为父子模型中的位置属性?

像这样:

parent.parents << Parent.create, 3

如果你想让它像你写的那样工作,你需要使用关系扩展:

has_many :parents, :through => :parent_child do
  def << (parent_object, position)
    proxy_association.owner.parent_child.create(:child_id => parent_object.id, :position => position)
  end
  alias :add, :<<
end

您可以直接创建ParentChild记录:

grand_parent = Parent.create
relationship = ParentChild.create(
                 parent_id: grand_parent.id, 
                 child_id:  parent.id, 
                 position:  3
               )

最新更新