【问题标题】:Mongoid, has_and_belongs_to_many, two sided associationMongoid,has_and_belongs_to_many,双边关联
【发布时间】:2015-12-07 05:06:59
【问题描述】:

我创建了具有自定义 has_and_belongs_to_many 关联的模型:

class Item
  include Mongoid::Document
  has_and_belongs_to_many :combinations, class_name: 'Item', inverse_of: :combinations
end

如果我有item1item2,当我做这样的事情时:

 item1.combinations << item2
 item1.save

 item1.combinations # returns [<Item2>]
 item2.combinations # returns []

这意味着关联是片面的。如何使这个协会成为两面性的?我错过了什么吗?

【问题讨论】:

    标签: ruby-on-rails ruby mongoid


    【解决方案1】:

    试试这个。我没有测试它,但应该可以工作。

    class Item
      include Mongoid::Document
      has_and_belongs_to_many :child_combinations, class_name: 'Item', inverse_of: :parent_combinations
      has_and_belongs_to_many :parent_combinations, class_name: 'Item', inverse_of: :child_combinations
    end
    

    那你就可以这样访问了

    item1.child_combinations
    item2.parent_combinations
    

    我希望这是你需要的。

    【讨论】:

    • 是否可以只使用一个has_and_belongs_to_many 关联?
    • 不,这是不可能的,因为 mongoid 需要双向关联。您必须指定如何建立关系。因此,如果您只提到一个has_and_belongs_to _many,mongoid 会查找相关模型中指定的关系,如果找不到,则不会创建关系。
    • 而且您不能将父子组合组合在一个数组中。您需要为父母和孩子指定两个不同的,否则它将始终是一侧的。
    • 但是为什么当我想关联不同的模型时它只需要一个has_and_belongs_to_many
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多