2014-10-03 88 views
2

使用Rails 3.2/Ruby 1.9的,比如我有以下類:ActiveRecord的關係與範圍

class Foo 
    has_many :bars 
end 

class Bar 
    scope :active, where(:active=>true) 
    # also tried 
    # scope :active, lambda{where(:active=>true)} 
    # scope :active, -> {where(:active=>true)} 
end 

現在,如果我有美孚(F)的實例,而我呢f.bars,我得到一個實例的ActiveRecord ::關係如預期。由於某種原因,雖然當我做f.bars.active時,我得到了未定義的方法active關係對象(我會購買這個作爲範圍在Bar類)。雖然我可以做f.bars.where(:active=>true)沒問題。我想我的問題是:

  1. 這裏發生了什麼?
  2. 如何使用活動範圍來達到所需的結果?
+0

上面的例子做的工作。我的情況是我的班級有一個錯誤(默默失敗),只有當我做Bar.active時才發現。 – psulightning 2014-10-08 15:22:25

回答

2

,必須用範圍陳述在拉姆達前,將正常工作:

scope :active, -> { where(:active=>true) } 
+0

我接受這個,因爲在句法上這是原始答案的正確答案。 – psulightning 2014-10-08 15:22:53