Hug*_*ugs 1 activerecord scope ruby-on-rails ruby-on-rails-3 rails-activerecord
我正在尝试查询使用联接的数据库来查找需要警报的用户.我的查询在为其编写的模型中工作正常,并且当传递的参数是显式时,它也可以在范围内工作.但是,当我将参数作为变量传递时,它不起作用.这是我的代码:
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
Run Code Online (Sandbox Code Playgroud)
我得到的错误是一个NameError未定义的局部变量或方法.但我会想到在rails控制台中传递变量的值如:
User.alerts_to_be_sent(5)
Run Code Online (Sandbox Code Playgroud)
没关系.感谢帮助,谢谢.
使用类方法是接受范围参数的首选方法.仍然可以在关联对象上访问这些方法[...]
所以编写类方法:
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
Run Code Online (Sandbox Code Playgroud)