将参数从视图传递到模型中定义的范围 [英] Pass a parameter from view to a scope defined in the model

查看:42
本文介绍了将参数从视图传递到模型中定义的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

我也尝试在我的模型中用简单的用户名替换 params[:username] 但是我得到了错误:

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>

有一个类似的问题,但你怎么能看到我做错了什么:Rails3 如何在命名范围内使用 :params?

There is a similar question, but how you can se i made something wrong: Rails3 How can I use :params in named scope?

谢谢!

推荐答案

您不能在模型中使用 params 变量.您可以做的是使用 lambda 将变量传递给作用域:

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)}

在您的控制器中:

@messages = Message.scope1_department(params[:username])

这篇关于将参数从视图传递到模型中定义的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆