Pass a parameter from view to a scope defined in the model

我只是一个虾纸丫 提交于 2020-01-05 08:30:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!