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?
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 thebefore_saveto anafter_createfilter and it then worked fine!In the end there was no problem with the Mongoid Associations, the problem was me.