How to use HATBM with various models

0

I will have the model Tag it will have relationship HABTM with POSTS .

But I want it to also have HABTM relationship with USERS because my goal is in the future to find posts that have the same tags as the user.

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

    
asked by anonymous 01.12.2014 / 02:14

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 query, for example, all posts that share tags with a certain user, do:

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

Or if this syntax does not work try

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

PS: There are more efficient ways to do this query but I will not focus on it.

    
22.03.2015 / 21:50
0

Good, I have the use of association has_many model, :through table

Following description of the documentation:

  

The has_many: through Association   A has_many: through association is often used to set up 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:    link

On some projects I have used gem acts-as-taggable-on which is very good for working with taggs, follow the link . I hope I have helped,

    
10.12.2014 / 14:30