1

我重构我的代码并尝试遵循约定“瘦控制器,胖模型”现在我尝试将查询移动到模型:

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?

谢谢!

4

2 回答 2

3

您不能params在模型中使用变量。您可以做的是使用 lambda 将变量传递给范围:

scope :scope1_department, ->(username){ where(sender_username: username, recipient_username: username)}

在您的控制器中:

@messages = Message.scope1_department(params[:username])
于 2013-10-29T19:44:14.223 回答
2

将参数传递给范围的方法:

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
于 2013-10-29T19:47:53.583 回答