轨道3:适用范围返回一个数组 [英] Rails 3: Scope returns an array
问题描述
我使用的范围,以获得该产品为特定用户:
I am using a scope to get an Item for a specific user:
在项目模型
belongs_to :user
scope :for_user, lambda { |user| where(:user_id => user) }
User模型
User model
has_many :items
问题
在调用 Item.includes(:用户).for_user(3)
数组返回,而不是一个ActiveRecord的关系。
我希望它表现得像 Item.includes。(:用户).find_by_user_id(3)
,它返回一个ActiveRecord的关系
When calling Item.includes(:user).for_user(3)
an Array is returned instead of an ActiveRecord relation.
I'd expect it to behave like Item.includes(:user).find_by_user_id(3)
, which returns a ActiveRecord relation.
感谢您的帮助。
推荐答案
如果你做一些调查,你会发现OU,它确实返回一个关系对象。
if you do some more investigation you'll find ou that it does indeed return a relation object.
但是它会在必要时将它转换成一个数组。
But it will when necessary convert it into an array.
也就是说,如果你在一个控制台,并说> Item.includes(:用户)。.for_user(3)
它会尝试对其进行检查,从而进行转换
Namely, if you're in a console and say > Item.includes(:user).for_user(3)
it will try to inspect it, and consequently do the conversion.
但无论如何下面的工作
scope = Item.includes(:user).for_user(3)
# does a db count
scope.count
# does a db select limit 1
scope.first
# does a full db select
scope.all
这篇关于轨道3:适用范围返回一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!