I'm having a problem where i'm trying to reference a model called user twice from a comment model.
The first instance is because a user can have many comments (as recipient)
But the other association is a comment has one author. Is that
references_one :user, :inverse_of :author
Would I then need another association in user for comments by that user as opposed to for that user.
embedded_in :user, :inverse_of => :commentsout
I hope it makes a bit of sense.
Maybe something like this makes more sense (pseudo-code)
user:
has_many:开发者_StackOverflow comments => author
can_be: author, recipient
comment:
belongs_to_many: users => recipients
has_one: user => author
If I understand the problem correctly you can define the associations like this:
class User
include Mongoid::Document
field :name, :type => String
references_many :comments, :inverse_of => :author
references_and_referenced_in_many :comments_received, :class_name => 'Comment', :inverse_of => :recipients
end
class Comment
include Mongoid::Document
field :text, :type => String
referenced_in :author, :class_name => 'User'
references_and_referenced_in_many :recipients, :class_name => 'User', :inverse_of => :comments_received
end
If the target cannot be inferred from the association name you need to add a :class_name parameter. This makes it possible to have multiple associations to the same class.
精彩评论