Rails polymorphic many to many association

后端 未结 4 403
无人及你
无人及你 2021-02-04 21:39

I\'m trying setup a generic sort of web of related objects. Let say I have 4 models.

  • Book
  • Movie
  • Tag
  • Category

I would lik

4条回答
  •  你的背包
    2021-02-04 22:32

    I have come up with a bit of solution. I'm not sure it's the best however. It seems you cannot have a polymorphic has_many through.

    So, I fake it a bit. But it means giving up the association proxy magic that I love so much, and that makes me sad. In a basic state, here is how it works.

    book = Book.find(1)
    book.add_related(Tag.find(2))
    book.add_related(Category.find(3))
    book.related        #=> [Tag#2, Category#3]
    book.related(:tags) #=> [Tag#2]
    

    I wrapped it up in a reusable module, that can be added to any model class with a single has_relations class method.

    http://gist.github.com/123966

    I really hope I don;t have to completely re-implement the association proxy to work with this though.

提交回复
热议问题