2012-03-09 67 views
2

我開始使用類方法作用域,因爲我需要將一些參數傳遞給作用域。以Rails的指南例如:Rails:如何讓類方法範圍處理無參數

def self.1_week_before(time) 
    where("created_at < ?", time) 
    end 

然而,在我的網站有時參數可以是零,在這種情況下,我想繞過劃定範圍,並轉到鏈中的下一個範圍。

我加入了,如果條件的方法:

def self.1_week_before(time) 
    if time 
     where("created_at < ?", time) 
    end 
    end 

然而,當我用這個方法在範圍的中間鏈,它會給出未定義的方法爲無:NilClass錯誤。我怎樣才能解決這個問題?

回答

4

這將返回nil,所以你得到的錯誤,當你鏈條:

def self.1_week_before(time) 
    if time 
    where("created_at < ?", time) 
    end 
end 

爲了防止這種情況,你可以回到scoped

def self.1_week_before(time) 
    if time 
    where("created_at < ?", time) 
    else 
    scoped 
    end 
end 
+1

我只是在這裏找到(http://stackoverflow.com/questions/3735838/empty-scope-with-ruby-on-rails)'scoped'應該比'all'更好。你可以改變它,我會接受它。 – lulalala 2012-03-09 04:25:44

+0

感謝您指出這一點...我自己學到了一些東西:-) – Mischa 2012-03-09 04:31:43