我正在使用MongoDB在应用程序中构建一个简单的票证系统。有一次,我能够创建门票,但现在我不是。用户模型如下:
class User
include Mongoid::Document
include Mongoid::Timestamps::Updated
has_many :initiated_tickets, :class_name => 'Ticket', :inverse_of => :initiator
has_many :assigned_tickets, :class_name => 'Ticket', :inverse_of => :assignee
Ticket模型如下:
class Ticket
include Mongoid::Document
include Mongoid::Timestamps::Updated
field :name
field :initiator_email
field :assignee_email
field :comment
belongs_to :alert
has_one :initiator, :class_name => 'User', :inverse_of => :initiated_tickets
belongs_to :assignee, :class_name => 'User', :inverse_of => :assigned_tickets
当我尝试创建一张票时,我收到来自Mongoid的错误声明:
Mongoid::Errors::InverseNotFound:
Problem:
When adding a(n) User to Ticket#initiator, Mongoid could not determine the inverse foreign key to set. The attempted key was 'initiated_tickets_id'.
我不确定这里出了什么问题。看起来两个都正确设置了inverse_of。知道为什么这不起作用,以前是什么时候?谢谢!
答案 0 :(得分:3)
您只需在inverse_of
方面定义belongs_to
即可。然而,has_many
方应定义foreign_key
。我有完全相同的关系,如下:
class User
has_many :initiated_tickets, foreign_key: "initiator_id", class_name: "Ticket"
has_many :assigned_tickets, foreign_key: "assignee_id", class_name: "Ticket"
class Ticket
field :initiator_id, :type => String
field :assignee_id, :type => String
belongs_to :initiator, inverse_of: "initiated_tickets" class_name: "User"
belongs_to :assignee, inverse_of: "assigned_tickets" class_name: "User"
修改
重写了我的答案,因为我原来错了。