0

我有一个协会:

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

但是是否可以设置一个附加属性,在这种情况下是 ParentChild 模型中的位置属性?

像这样的东西:

parent.parents << Parent.create, 3
4

2 回答 2

0

您可以直接创建ParentChild记录:

grand_parent = Parent.create

relationship = ParentChild.create(
                 parent_id: grand_parent.id, 
                 child_id:  parent.id, 
                 position:  3
               )
于 2013-09-11T12:44:06.363 回答
0

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

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
于 2013-09-11T12:50:13.843 回答