如何按多个字段过滤结果?
我正在 ruby on Rails 中开发一个调查应用程序,在结果页面上,我想让用户通过我在调查开始时提出的一系列人口统计问题来过滤答案。
例如,我询问用户的性别和职业是什么。所以我正在考虑设置性别和职业的下拉列表。两个下拉列表都默认为全部,但如果用户选择女性和营销人员,那么我的结果页面将仅来自女性营销人员的答案。
我认为这样做的正确方法是使用named_scopes,其中我对每个人口统计问题都有一个named_scope,在本例中是性别和职业,它将从下拉列表中获取经过净化的值以在有条件时使用,但我'我不确定如何动态创建named_scope链,因为我有大约5个人口统计问题,大概其中一些将被设置为全部。
I am working on a survey application in ruby on rails and on the results page I want to let users filter the answers by a bunch of demographic questions I asked at the start of the survey.
For example I asked users what their gender and career was. So I was thinking of having dropdowns for gender and career. Both dropdowns would default to all but if a user selected female and marketer then my results page would so only answers from female marketers.
I think the right way of doing this is to use named_scopes where I have a named_scope for every one of my demographic questions, in this example gender and career, which would take in a sanitized value from the dropdown to use at the conditional but i'm unsure on how to dynamically create the named_scope chain since I have like 5 demographic questions and presumably some of them are going to be set to all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将命名范围链接在一起:
但是我更喜欢使用 has_scope gem:
如果您使用 has_scope 与 inherited_resources< /a>,您甚至不需要定义索引操作。
You can chain named scopes together:
I prefer however to use the has_scope gem:
If you use has_scope with inherited_resources, you don't even need to define the index action.
如果您以这种方式编写命名范围,则可以将它们全部链接起来,并且如果您的参数之一为空,则不会中断。
你可以像这样链接所有的方法。最后作为过滤,你可以有这样的:
If you write named scopes in this way, you can have all them chained, and if one of your params will be blank wont breaks.
And you can chain all of your methods like this. Finally as a filtering you can have like:
尝试这样的:
或者这样的:
这对我来说非常好!
Try some like this:
Or like this:
That work for me very nice!