Simonp27
Simonp27

Reputation: 143

Rails Active Record Association Query

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

Answers (1)

jvillian
jvillian

Reputation: 20263

Assuming:

  1. Channel belongs_to Group
  2. You have a @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 Channels belonging to all Groups 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

Related Questions