开发者

Mongoid Associations not working

开发者 https://www.devze.com 2023-04-09 20:44 出处:网络
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

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 work开发者_如何学Gos but if I do category.articles I get []. Any ideas why?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号