当前位置: 动力学知识库 > 问答 > 编程问答 >

Rails eager loading, includes and session attributes

问题描述:

I have a model with Missions, Users and Wits.

Wits belong to Missions and to a User.

I want to load a list of all the missions and eager load the wit for a specific user.

I need to do a LEFT OUTER JOIN and add a condition to the join.

Here is what is working for now :

Mission.joins("LEFT OUTER JOIN wits ON wits.mission_id = missions.id AND wits.user_id = #{current_user.id}")

Then in my list I can do mission.wits.first to get the wit belonging to the right user.

But it's not very rails friendly, and I have to check for the .loaded? attribute to avoid loading all the wits if the condition is not met.

Is there a better way, hopefully using scopes, to get the job done ? Maybe adding a new virtual attribute to Mission, but I'd like to avoid making 20 calls to the database on each list.

UPDATE : In the end I'd like to see a list of mission, and for each mission the Wit status for the current_user. I'm using a gem called to acts_as_api to create a view of my list in JSON, but I cannot access a session variable inside the model, this is why I'm looking at this eager loading stuff, to load all the stuff I need from the controller.

Thanks for your help

网友答案:

Why not do something like

Wit.includes(:mission).where(:user_id => params[:user_id])

Is there a reason you're querying from the Mission when it sounds like you really want just the wits? Also if you do want a list of the associated missions you could do something like this too

Wit.includes(:mission).where(:user_id => params[:user_id]).select(&:mission).uniq
网友答案:

This should work for you:

Mission.joins(:wits).where(:wits => { :user_id => params[:user_id] }) Or
Mission.joins(:wits).where('wits.user_id' => params[:user_id] )
分享给朋友:
您可能感兴趣的文章:
随机阅读: