Reputation: 935
I am trying to query a db that uses a join to find users that require an alert. My query works fine in the model it is written for and it also works through the scope when the parameter being passed is explicit. However when I pass the parameter as a variable it does not work. Here is my code:
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
The error I am getting is a NameError undefined local variable or method. But I would have thought passing the value of the variable in the rails console like:
User.alerts_to_be_sent(5)
would be ok. Help would be appreciated thanks.
Upvotes: 1
Views: 2520
Reputation: 7458
I think you're looking for the lambda scope syntax
scope :alerter, lambda { |number| find_users_to_alert(number) }
scope :alerts_to_be_sent, lambda { |number| joins(:alerts) & Alert.alerter(number) }
Upvotes: 2
Reputation: 434985
From the Active Record Query Interface Guide:
Using a class method is the preferred way to accept arguments for scopes. These methods will still be accessible on the association objects [...]
So write class methods instead:
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
Upvotes: 5