1

I have a Rails model called User. There are two different types of users. Some users have company_profiles in a separate table.

In my controller for my page view, I'd only like to display those users who have company_profiles. I'd also like to display their user info and their company_profile info too.

I'm not sure how to handle this in my controller and view.

What should be in my index method?

def index
  @users = User.scoped # ?????
end

And how do I loop through each user with a company profile on the index page?

<% @users.each do |user| %>
  <p>
    <%= user.email %>
    <%= user.company_profile.poc_first_name %>
  </p>
<% end %>
Violeta
  • 700
  • 7
  • 16
John Gerard
  • 299
  • 4
  • 19
  • Possible duplicate of https://stackoverflow.com/questions/18234602/rails-active-record-querying-association-with-exists – Josh Brody Sep 20 '19 at 04:18

2 Answers2

2

Now you mentioned you want to show users only for which company_profile exists. So in your controller method following should be in the index method

def index
   @users = User.left_outer_joins(:company_profile).where("company_profiles.id is  NOT NULL")
end

Then in your views you can get company_profile's poc first name as follows

<% @users.each do |user| %>
    <p><%= user.email %>
        <%= user.company_profile.poc_first_name %>
    </p>
<% end %>
user3775217
  • 4,675
  • 1
  • 22
  • 33
  • Why a left _outer_ join but then removing the rows which are empty on the right side? Isn't that basically an _inner_ join? – spickermann Sep 23 '19 at 10:04
1

Making an INNER JOIN when loading the records from the database should work:

def index
  @users = User.joins(:company_profile)
end
spickermann
  • 100,941
  • 9
  • 101
  • 131