Reputation: 426
In my problem I need posts to each belong to Category but I also want every post to be in a second category. Such that one post could be in "News" and another in "Sports" but they would both be in "Everything". Currently my associations are like this:
class Article
include Mongoid::Document
belongs_to :category
belongs_to :home_category, :class_name => 'Category'
end
class Category
include Mongoid::Category
has_many :articles
end
Currently the normal article.category works fine. However article.home_category
sets on the Article object but does not reciprocate to Category object. So if I set article.home_category=category
it works but if I do category.articles I get [].
Any ideas why?
Upvotes: 1
Views: 620
Reputation: 426
So it turns out that my problem was that I was setting the category using a before_save
, which incidentally turns out to not work out well when it is called on an unpersisted article. I fixed the problem by switching the before_save
to an after_create
filter and it then worked fine!
In the end there was no problem with the Mongoid Associations, the problem was me.
Upvotes: 1
Reputation: 33732
the way you set up your relation, it's a 1:n relation between Article and Category ... that means that you can't have many categories for an article.
You should change it to a n:m relationship, see:
http://mongoid.org/docs/relations/referenced/n-n.html
class Article
include Mongoid::Document
has_and_belongs_to_many :categories
end
class Category
include Mongoid::Category
has_and_belongs_to_many :articles
end
Or you could try acts_as_taggable for Mongoid :
http://abhishiv.tumblr.com/post/3623498128/introducing-acts-as-taggable-for-mongoid
Having two relations to Categories as you have in your example code is probably not a good idea.
Upvotes: 1