2011-03-06 45 views
0

已經繼承了一個項目,我覺得這樣的代碼,來搜索代碼庫一組記錄:加限制菊花鏈查詢在軌

Listing.category_id_equals(category_id).city_id_equals(city.id).end_date_greater_than(Time.now.utc).start_date_less_than(Time.now.utc).validated_equals(true) 

這工作,但脆弱的,因爲如果我不想包含任何條件,我需要一個新的方法。所以,使用proc的我現在有:

def self.for_cat_and_city cat=nil, city=nil 
    base = proc { |o| o.end_date_greater_than(Time.now.utc).start_date_less_than(Time.now.utc).validated_equals(true)} 
    city_query = proc { |o, city| o.city_id_equals(city.id)} 
    cat_query = proc { |o, cat| o.category_id_equals(cat.id)} 
    limit = proc { |o, limit| o.limit(limit)} 
    unless cat.nil? 
    return city_query.call(cat_query.call(base.call(Listing),cat), city) unless city.nil? 
    return cat_query.call(base.call(Listing), cat) 
    end 
    return city_query.call(base.call(Listing), city) unless city.nil? 
    return base.call(Listing) 
end 

哪個工作得很好。但現在我需要爲記錄數添加限制。我如何在上面做的事情的範圍內輕鬆地做到這一點?

回答

0

嘗試只是增加limit到鏈的末端,像這樣:

listings = Listing.category_id_equals(category_id).city_id_equals(city.id).end_date_greater_than(Time.now.utc).start_date_less_than(Time.now.utc).validated_equals(true).limit(30) 

運作的?

+0

對不起我錯過了這個...現在項目結束了...所以我不能說... – 2011-10-03 14:36:08

+0

嗯 - 我自己也有點晚了:) – 2012-01-09 20:10:44