如何使用named_scope来过滤模型中的记录
我有一个带有“描述”字段的模型“产品”。现在我想在索引页面中有一个链接,单击该链接将显示描述为空白(空)的所有产品。
在模型中,我定义了一个像这样的named_scope,
named_scope :no_description, :conditions => { :description => "" }
我通过在控制台上调用Product.no_description.count来检查named_scope是否有效。
据我所知,控制器应该处理来自“索引”操作链接的过滤器请求,但能够将其与默认的查看所有产品区分开来。
def index
@products = Product.all
...
我的问题是让控制器处理不同的请求,为视图上的链接设置什么路由以及视图上的实际链接。希望我解释了我的问题。
I have a model "Product" with a "description" field. Now I want to have a link in the index page that when clicked will show all products where the description is blank (empty).
In the model I have defined a named_scope like this
named_scope :no_description, :conditions => { :description => "" }
I have checked that the named_scope works by calling Product.no_description.count on the console.
As far as I know, the controller is then supposed to handle the filter request from the link on the "index" action but be able to distinguish it from the default which is view all products.
def index
@products = Product.all
...
My problem is getting the controller handle the different request, what route to setup for the link on the view and the actual link on the view. Hope I explained my problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的链接传入参数,您可以检查该参数并在索引操作中使用命名范围:
在您看来,您可以使用类似以下内容的内容:
If your link passes in a parameter, you can check for that and use the named scope in the index action:
In your view you can use something like:
您可以采取两种基本方法。您可以设置新的路由和控制器操作来显示无描述的产品,或者可以在超链接上使用查询字符串参数来进行区分。我会采用第二种方法,以避免过多的操作使控制器变得混乱。
假设您使用 RESTful,您的链接将如下所示路由:
这是控制器操作,它简单地查找参数是否存在(即它不关心它有什么值):
There are two basic approaches you can take. You could set up a new route and controller action for displaying the description-less products, or you could use a query string parameter on the hyperlink to make the distinction. I would go with the second approach to avoid cluttering up the controller with too many actions.
Your link will look something like this, assuming you're using RESTful routing:
And here's the controller action, which simple looks for the existence of the parameter (i.e. it doesn't care what value it has):