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