【发布时间】:2017-09-26 13:57:09
【问题描述】:
我有一个关于 mongoid / rails 关系的问题,我知道这类问题有很多话题,但我没有找到任何对我有帮助的话题.. 我有这些模型:
class Project
include Mongoid::Document
belongs_to :owner, :class_name => 'User', inverse_of: :projects
has_many :members
end
class Member
include Mongoid::Document
belongs_to :project, inverse_of: :members
belongs_to :user
end
class User
include Mongoid::Document
has_many :projects, inverse_of: :user
end
当我尝试将用户记录为会员时,出现此错误:
Mongoid::Errors::InverseNotFound (
message:
When adding a(n) User to Project#members, Mongoid could not determine the inverse foreign key to set. The attempted key was 'project_id'.
summary:
When adding a document to a relation, Mongoid attempts to link the newly added document to the base of the relation in memory, as well as set the foreign key to link them on the database side. In this case Mongoid could not determine what the inverse foreign key was.
resolution:
If an inverse is not required, like a belongs_to or has_and_belongs_to_many, ensure that :inverse_of => nil is set on the relation. If the inverse is needed, most likely the inverse cannot be figured out from the names of the relations and you will need to explicitly tell Mongoid on the relation what the inverse is.
Example:
class Lush
include Mongoid::Document
has_one :whiskey, class_name: "Drink", inverse_of: :alcoholic
end
class Drink
include Mongoid::Document
belongs_to :alcoholic, class_name: "Lush", inverse_of: :whiskey
end):
我不明白为什么,我认为关系和逆关系有问题,但我不知道如何解决这个问题。
【问题讨论】:
标签: ruby-on-rails mongoid