HUSTEN
HUSTEN

Reputation: 5197

How can I use eager loading in this case?

Supposing I have these 6 models such as

User has one Profile.
Then each Profile has those who are gender_id, country_id, and prefecture_id.
User also has many Cars

I'm stating asssociation just like this.

models/user.rb

has_one :profile
has_many :cars

scope :confirmed, where("sign_in_count != ?",0)
paginates_per 10

models/profile.rb

belongs_to :user
belongs_to :gender
belongs_to :country
belongs_to :prefecture

models/gender.rb

has_many :user_profile

models/country.rb

has_many :user_profile

models/prefecture.rb

has_many :user_profile

models/car.rb

belongs_to :user

And here's my question!
How can I fix my code in controller, and view?

This my current codes.

CONTROLLER

@users = User.confirmed.joins(:profile).page(params[:page]).order('profiles.total_point DESC')

VIEW

<% @users.each do |user| %>
    <tr>  
        Username: <%= user.username %> <br />
        Total Point: <%= user.profile.total_point %> <br />
        Gender: <%= user.profile.gender.data %> <br />
        Country: <%= user.profile.country.data %> <br />
        Prefecture: <%= user.profile.prefecture.data %> <br />
        The number of the cars that the user owns: <%= user.cars.count %> <br />
    </tr>        
<% end %>

Upvotes: 0

Views: 34

Answers (1)

hedgesky
hedgesky

Reputation: 3311

Updated

I think, you should try this approach:

@users = User.includes(:cars, profile: [:gender, :country, :prefecture]).confirmed.page(params[:page]).order('profiles.total_point DESC')

Does it work?

Upvotes: 1

Related Questions