jacques Mesnet jacques Mesnet - 3 years ago 289
MySQL Question

Use an element form join table

I would like to select the groups of my user where the join table is marked as favorit: true.

So I have User which have Groups across a join table named UsersGroup. The UsersGroup model have of course a variable group_id and user_id, but also a variable favorit.

So I would like to call the favorit groups of my users. But I don't know how to write it.

I've tried something like this :

current_user.groups.joins(:users_group).where(:users_group => {:favorit => true})


current_user.groups.where(users_group.favorit == true)

Do you have a solution for this kind of requests ?

Answer Source

You can use:

current_user.user_groups.where(favorit: true)

If you want to access the groups from this, you can get the group from the user_groups found above. I.E.

favorits = current_user.user_groups.where(favorit: true).includes(:group)

Notice the includes in there to eager load the groups and avoid any N + 1 issues.

Does that do what you're looking for?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download