ruby-on-rails-3 - named_scope 和 .first?

标签 ruby-on-rails-3 named-scope

我可以返回一个对象集合,只有一个 (: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

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

最佳答案

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

def self.profile
  where(:association => 'owner', :resource_type => 'Profile').first
end

请注意,对于 Rails 3,您应该使用 where(...)语法,以及在做 .first 时,您无需指定限制。

关于ruby-on-rails-3 - named_scope 和 .first?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6299065/

相关文章:

ruby-on-rails - ActiveRecord named_scope, .scopes

ruby-on-rails-3 - 在模型导轨 3 中搜索多列

升级到Snow Leopard后的Mysql2 gem问题

ruby-on-rails - rake 分贝 :test:prepare task deleting data in development database

ruby-on-rails-3 - 即使使用 "set :use_sudo, false"Capistrano 也使用 sudo

mysql - 带有 ORDER BY CASE 子句的范围无法正常工作

ruby-on-rails - has_one,:through => model VS simple method?

ruby-on-rails - Rails has_many 与 finder_sql 和 name_scope 组合返回 nil

ruby-on-rails - 多个 has_many 通过关系

ruby-on-rails - 这可以与 rails 中的 named_scope 一起使用吗?