【发布时间】:2013-04-04 09:03:18
【问题描述】:
我有一个关于使用 named_scopes 的问题:
假设我有以下模型(我知道我提供的一些 named_scope 可以直接通过活动记录实现,但它们仅用于示例):
def person
named_scope :older_then, lambda {|min_age| {:conditions => ["age > ?",min_age]} }
named_scope :by_first_name, lambda {|name| {:conditions => {:first_name => name}}}
def self.some_function(age_param, name_param)
chain = Person
chain = chain.older_then(age_param) unless age_param.blank?
chain = chain.by_first_name(name_param) unless name_param.blank?
chain.all
end
end
现在假设我想打电话:
people = Person.some_function(20, "john")
在构建 named_scopes 链时,Rails 将对数据库进行 2 次调用:
select * from persons where age>20
select * from persons where age>20 and name='john'
显然,我想要的只是第二个查询的结果,并不打算在构建 named_scopes 链时执行第一个查询。任何想法我在这里做错了什么/按条件组合多个 named_scope 的正确方法是什么?
顺便说一句,我使用的是 Ruby 1.8.7 它的旧版本,我知道... :(
【问题讨论】:
-
除非你也使用旧版本的 Rails,否则你应该使用
scope,而不是named_scope。 -
@meagar:OP 似乎正在使用 Rails 2.x
-
是的,使用 rails 2.3.11
标签: ruby-on-rails ruby