【问题标题】:Mongoid::Errors::MixedRelations + saveMongoid::Errors::MixedRelations + 保存
【发布时间】:2012-07-20 10:06:40
【问题描述】:

我有 3 个模型:

class Interest
  include Mongoid::Document

  has_many :user_hobby
end

class UserHobby
 include Mongoid::Document
  field :contacts, :type => Array

  belongs_to :interest, :foreign_key => "interest", inverse_of: nil
  belongs_to :interest, :foreign_key => "related_interests", inverse_of: nil
  embedded_in :user
end

class User
 include Mongoid::Document
 embeds_many :user_hobby
end

我必须添加 user 和 user_hobby 之间的嵌入关系,但在那之后(在我的测试中) 当我想保存兴趣时出现此错误:

Mongoid::Errors::MixedRelations:由于 UserHobby 已嵌入,因此不允许通过关系关联从兴趣文档引用 (n) 个 UserHobby 文档。

我看了这个话题,但也没有帮助我Mongoid::Errors::MixedRelations

谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 mongodb mongoid


    【解决方案1】:

    这里的主要问题是您的 UserHobby 模型嵌入到了 User 中。根据 mongodb,如果一个文档被嵌入,它不能被任何其他模型引用,除了它被嵌入的模型。如果你想从其他模型引用 UserHobby 文档,那么 UserHobby 和 User 不应该有嵌入关系。

    【讨论】:

    • 你确定有像这个链接这样的关系有任何解决方案吗? stackoverflow.com/questions/8437181/mongoiderrorsmixedrelations
    • 在您在该嵌入式文档中发布的问题中有其他模型的参考。在 UserHobby 中,您可以拥有没有反向关系的 has_many 兴趣,但是从 User 以外的其他模型引用 UserHobby 是不可接受的。就像你在兴趣中所做的那样。
    • 是的,没有解决方案,您可以在嵌入文档中引用任何其他文档,但您不能从除嵌入文档之外的任何其他文档中引用嵌入文档。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多