has_many :through with has_and_belongs_to_many in Rails
Question
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 indicated below:
class Tag < ActiveRecord::Base
has_many :posts_tag
has_and_belongs_to_many :posts
end
class Post < ActiveRecord::Base
has_many :posts_tag
has_many :tags, :through => posts_tag
end
class PostsTag < ActiveRecord::Base
belongs_to :tag
belongs_to :post
end
The reason I use has_and_belongs_to_many
is because a tag
belongs to many posts.
I did look into the Rails Association guide and see that they don't mention this case for a many-to-many relationship. I, however, did try this and running it in Rails didn't yield any behavior and from the small test database that I built, also seemed to return the correct results for post.tags
and tag.posts
- where post
and tag
refer to an instance of the Post
and Tag
models respectively.
Is this correct usage or does it have any side affects that I am not aware of? Also, if it is correct, is this the Rails way of achieving this?
Thanks!
No correct solution