jacques Mesnet jacques Mesnet - 7 months ago 57
Ruby Question

Access data from a join table

I would like to select a user's groups where the join table is marked with

favorit: true
.

I have
User
which has
Groups
through a join table named
UsersGroup
. The
UsersGroup
model have the variables
group_id
and
user_id
, but also a variable
favorit
.

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)
favorits.map(&: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