named_scope和.first?

And*_*ank 4 named-scope ruby-on-rails-3

我可以返回一个对象集合,只有一个(:limit => 1)但是有没有办法只返回.first()对象,就像不在集合中一样?

named_scope :profile, :conditions => {:association => 'owner', :resource_type => 'Profile'}, :limit => 1    # => collection of 1 profile but I want the profile only NOT in a collection or array
Run Code Online (Sandbox Code Playgroud)

解决方法只是将.first()应用于结果,但我只想清理代码并使其不易出错.

Dyl*_*kow 7

您可能需要创建一个类方法:

def self.profile
  where(:association => 'owner', :resource_type => 'Profile').first
end
Run Code Online (Sandbox Code Playgroud)

请注意,对于Rails 3,您应该使用where(...)语法,并且在执行时.first,您不需要指定限制.


cor*_*ard 5

首先,如果你使用Rails 3,你应该使用scope而不是named_scope.同样的,不同的,错误的,名称(named_scope仍然有效,但不推荐使用).现在已经不在了......

范围(或命名范围)采用两个参数(一个符号和一个lambda或一个哈希),并在该模型上定义一个返回ActiveRecord :: Relation的类方法,这就是您能够在其上链接方法的原因.

first,find或者all,从数据库中返回实际结果.因此,它不适用于范围.

总而言之,您可以在模型上定义自己的类方法,以提供您想要的行为(因为我在键入时已经回答了2个人).实际上建议使用Rails社区中许多备受尊重的开发人员使用范围.因为使用scope类宏本身只是定义了类方法,所以这并没有真正的缺点,它具有灵活性的好处(就像你的情况一样).