活动记录:与参数渴望负荷协会 [英] Active Record: Eager load association with parameter

查看:118
本文介绍了活动记录:与参数渴望负荷协会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号:

class Rating < ActiveRecord::Base
  belongs_to :item
  belongs_to :user
end

class Item < ActiveRecord::Base
  has_many :ratings
end

我要取的所有项目,并通过特定的用户进行的评级,显示当前用户的等级(如果存在的话!)每个项目旁边。

I want to fetch all items, and the ratings made by a specific user to show the current user's rating (if it exists!) next to each item.

我已经试过......

I've tried...

Item.includes(:ratings).where('ratings.user_id = ?', user_id)

...但是,这不给我的项目,没有收视率。

...but that don't give me the items with no ratings.

我首先想到的是用一个参数一个的has_many关联,然后再传递参数与包括法。但是,这似乎并不存在。

My first thought was a has_many association with an argument, and then pass that argument with the includes method. But that doesn't seem to exist.

如何获得的所有帖子,并渴望加载关联过滤参数上没有做N + 1查询或加载所有实体到内存?

推荐答案

第1步

请在 CURRENT_USER 在模型层访问(一个技术此处概述:的 http://stackoverflow.com/a/2513456/163203

Make the current_user accessible in the model layer (one technique is outlined here: http://stackoverflow.com/a/2513456/163203)

第2步

添加一个协会与在运行时间被评估的条件。

Add an association with a condition that gets evaluated during run time.

轨道2

class Item < ActiveRecord::Base
  has_many :ratings
  has_many :current_user_ratings, 
           :class_name => "Rating", 
           :conditions => 'ratings.user_id = #{User.current_user.try(:id)}'
end

的Rails 3.1及以上

class Item < ActiveRecord::Base
  has_many :ratings
  has_many :current_user_ratings, 
           :class_name => "Rating", 
           :conditions => proc { ["ratings.user_id = ?", User.current_user.try(:id)] }
end

第3步

Item.includes(:current_user_ratings)

这篇关于活动记录:与参数渴望负荷协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆