链接named_scopes

时间:2013-04-04 09:03:19

标签: ruby-on-rails ruby

我有一个关于使用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将对db进行2次调用:

select * from persons where age>20
select * from persons where age>20 and name='john'

显然我想要的只是第二个查询的结果,并没有打算在构建named_scopes链时执行第一个查询。任何想法我在这里做错了什么/什么是按条件组合多个named_scope的正确方法?

顺便说一下,我使用的是Ruby 1.8.7,我知道...... :(

1 个答案:

答案 0 :(得分:1)

改变这个:

def self.some_function(age_param, name_param)
   chain = Person

为:

def self.some_function(age_param, name_param)
   chain = self

这将使原始链保持原样而不是开始新链。