MKK
MKK

Reputation: 2753

How can I fetch associated tables with using includes()?

There are 4 tables such as codes, users, user_profiles, and communities.

The associations are set up just like this below.

Code belongs_to :user
Code belongs_to :community

User has_many :codes
User has_one :user_profile

UserProfile belongs_to :user

Community has_many :codes

If I want to use includes()

@communities = current_user.get_up_voted(Community)
@communities_ids = @communities.pluck(:id)

@codes = Code.includes(:user) \
             .where(:community_id => @communities_ids) \
             .order("users.active_at DESC") \
             .page(params[:page]) \
             .includes(:community, user: [:user_profile])

This won't work because of this part here.

includes(:community, user: [:user_profile])

But if I switch it to

includes(:community)

that works...

How can I add user_profile into includes?

Upvotes: 0

Views: 52

Answers (1)

pdobb
pdobb

Reputation: 18037

Your approach looks like it should basically be working... I would try using a Hash without the array for your .includes since there's only one association being added. And I would also suggest combining the 2 different .includes statements into one. So like this:

@codes = Code.includes(:community, user: :user_profile)
             .where(community_id: @communities_ids)
             .order("users.active_at DESC")
             .page(params[:page])

Upvotes: 1

Related Questions