0
votes

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?

1
May be you can get some idea from stackoverflow.com/questions/18473529/… - RAJ
@RAJ... Thanks I took a look at the link. However it looks like the old way of coding style. Not for RoR 3 or higher - MKK
I edited your code a little for readability (and check out pluck, it's a nest method to use instead of collect) - Mike Szyndel
Does it work if you just includes(:community, :user)? - Mike Szyndel

1 Answers

1
votes

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])