我重构我的代码并尝试遵循惯例“瘦控制器,胖模型” 现在我尝试将查询移动到模型:
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)
在我的控制器中我有:
@messages = Message.scope_department(params[:username])
现在我的模型代码出现了这个错误:
undefined local variable or method `params' for #<Class:0x85d0b80>
我也尝试在我的模型中用简单的用户名替换params [:username],但后来我得到了错误:
undefined local variable or method `username' for #<Class:0x459fa50>
有一个类似的问题,但你怎么能说错了: Rails3 How can I use :params in named scope?
谢谢!
答案 0 :(得分:3)
您无法在模型中使用params
变量。你可以做的是使用lambda:
scope :scope1_department, ->(username){ where(sender_username: username, recipient_username: username)}
在您的控制器中:
@messages = Message.scope1_department(params[:username])
答案 1 :(得分:1)
将参数传递给范围的方法:
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