1

我想查詢一個使用連接來查找需要警報的用戶的數據庫。我的查詢在它爲其編寫的模型中正常工作,並且在傳遞的參數是顯式的時它也可以在範圍內工作。但是,當我將參數作爲變量傳遞時,它不起作用。這裏是我的代碼:在Rails 3中傳遞的跨作用域參數

class Alert < ActiveRecord::Base 
    belongs_to :user 
    attr_accessible :first_alert, :second_alert, :third_alert, :user_id 
    def self.find_users_to_alert(time) 
    where(:third_alert => time) 
    end 
    scope :alerter, find_users_to_alert (here is where i want to pass param) 
end 

class User < ActiveRecord::Base 
    has_many :alerts 
    attr_accessor :password 
    attr_accessible :name, :email, :password, :password_confirmation 

    scope :alerts_to_be_sent, joins(:alerts) & Alert.alerter 
end 

我得到的錯誤是一個NameError未定義的局部變量或方法。但我會想在滑軌控制檯中傳遞變量的值,例如:

User.alerts_to_be_sent(5) 

會好的。幫助,將不勝感激。

回答

5

Active Record Query Interface Guide

使用類方法是接受範圍參數的首選方式。這些方法仍然是對關聯對象訪問[...]

所以寫類的方法來代替:

class Alert < ActiveRecord::Base 
    def self.alerter(t) 
    find_users_to_alert(t) 
    end 
end 

def User < ActiveRecord::Base 
    def self.alerts_to_be_sent(t) 
    joins(:alerts) & Alert.alerter(t) 
    end 
end 
+0

謝謝你救了我很多挫折。我根本不需要使用範圍。組合的類方法很好地工作。 – Hugs 2012-02-08 22:10:45

2

我認爲你正在尋找的拉姆達範圍語法

scope :alerter, lambda { |number| find_users_to_alert(number) } 
scope :alerts_to_be_sent, lambda { |number| joins(:alerts) & Alert.alerter(number) } 
+0

這也會起作用,但類方法是「首選」方式,但偏好會有所不同。 – 2012-02-08 22:17:03

+0

是的,個人而言,我會將alerts_to_be_sent範圍作爲類方法,因爲它很複雜,但有時範圍的簡潔性對我來說更好看。再次,這是一個偏好問題。 – 2012-02-09 01:36:23

+0

請注意,爲什麼他們更喜歡 - 範圍可以鏈接等 - 例如'current_user.products.available'我不認爲你可以在這裏實現'available'作爲一個類的方法。 – DavidC 2013-01-30 00:01:38

相關問題