问题
Im refactoring my code and try to follow the convention "Skinny controllers, fat models" Now i tried to move a Query to the model:
scope :scope1_department, where(sender_username: params[:username], recipient_username: params[:username])
scope :scope2_department, where(recipient_username: params[:username])
scope_department = scope1_department.merge(scope2_department).sort_by(&:created_at)
And in my controller i have:
@messages = Message.scope_department(params[:username])
Now i get this error for my model code:
undefined local variable or method `params' for #<Class:0x85d0b80>
I also tried in my model to replace the params[:username] with simply username but then i get the error:
undefined local variable or method `username' for #<Class:0x459fa50>
There is a similar question, but how you can se i made something wrong: Rails3 How can I use :params in named scope?
Thanks!
回答1:
You can not use params
variable in your model. What you can do is to pass a variable to the scope using a lambda:
scope :scope1_department, ->(username){ where(sender_username: username, recipient_username: username)}
In your controller:
@messages = Message.scope1_department(params[:username])
回答2:
Ways to pass arguments to a scope:
class Message < ActiveRecord::Base
# a scope using a lambda
scope :scope2_department, lambda { |name| where(recipient_username: name) }
# same as above, ruby 1.9+ syntax
scope :scope3_department, ->(name) { where(recipient_username: name) }
# a class method
def self.scope4_department(username)
where(recipient_username: username)
end
end
来源:https://stackoverflow.com/questions/19667615/pass-a-parameter-from-view-to-a-scope-defined-in-the-model