How to use HATBM with multiple models

Asked

Viewed 49 times

0

I’ll have the model Tag he’s gonna have a relationship HABTMwith POSTS.

But I want him to have a relationship too HABTM with USERS because my goal is in the future to be able to find posts that have the same tags as the user.

How do I do it? Create a common relationship by creating two separate tables for both? And then, how do I search posts that have the same tags as a user?

2 answers

1

Yes, you will have to create separate relationships. In total you will have 5 tables:

users
tags_users
tags
posts_tags
posts

Then if you want to consult, for example, all posts that share tags with a particular user, do:

user = Users.first
posts.joins(tags: :users).where(tags: {user: user})

Or if this syntax doesn’t work try

posts.joins(tags: :users).where('users.id' => user)

PS: there are more efficient ways to do this query but I won’t focus on that.

  • One more comment. You can use the option :through in has_and_belongs_to_many. I never tried, but after you are with the 5 tables and the relationships working you can try adding this option.

0

Buenas, I emerged the use of the association has_many model, :through table

Follows description of the documentation:

The has_many :through Association A has_many :through Association is often used to set up a Many-to-Many Connection with Another model. This Association indicates that the declaring model can be Matched with zero or more instances of Another model by proceeding through a third model. For example, consider a Medical Practice Where Patients make appointments to see Physicians. The Relevant Association declarations could look like this: http://guides.rubyonrails.org/association_basics.html

In some projects I used Gem acts-as-taggable-on which is very good for working with Taggs, follows the link. I hope I’ve helped,

Browser other questions tagged

You are not signed in. Login or sign up in order to post.