Reputation: 143
I have the following models which looks like:
user.rb
has_many: groups
group.rb
has_many: channels
I want a query that returns a list of the "name" fields for all the channels belong to all the groups belonging to User.
What I have below doesn't work, any guidance appreciated.
Group.all.where("user_id = ?", 1).joins(:channels)
Upvotes: 1
Views: 28
Reputation: 20263
Assuming:
belongs_to
Group@user
I believe you should be able to do:
Channel.where(group: @user.groups).pluck(:name)
Which should return an array
(which I assume is what you mean by list
) of the name
attribute of all Channel
s belonging to all Group
s which belong to @user
.
In your case (indicated in your comment to your original post which really should have been an edit), you should do:
<% @user_groups.each do |group| %>
<tr>
<td>
<%= group.name %>
</td>
<td>
<%= group.channels.pluck(:name) %>
</td>
</tr>
<% end %>
Upvotes: 2