将参数从视图传递到模型中定义的范围

时间:2013-10-29 19:38:24

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

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

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?

谢谢!

2 个答案:

答案 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