has_many :through with has_and_belongs_to_many in Rails

后端 未结 2 1845
醉酒成梦
醉酒成梦 2021-01-27 01:05

In Rails - what is the effect of using has_many :through with has_and_belongs_to_many? Consider having two models - Posts and Tags which have a many-to-many relationship as indi

2条回答
  •  醉话见心
    2021-01-27 01:39

    While I'm not sure of the exact effects of having a has_many :through on one side of a relationship and a has_and_belongs_to_many on the other side, I do know that the more correct way, would be to use a reversed has_many :through like so:

    class Tag < ActiveRecord::Base
      has_many :posts_tag
      has_many :posts,  :through => posts_tag
    end
    

    Keeping the other relationships the same.

提交回复
热议问题