简体   繁体   English

如何按多个字段过滤结果?

[英]How to filter results by multiple fields?

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. 我正在使用ruby on rails和结果页面上的调查应用程序,我想让用户通过我在调查开始时提出的一系列人口统计问题来过滤答案。

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. 我认为这样做的正确方法是使用named_scopes,我的每个人口统计学问题都有一个named_scope,在本例中为性别和职业,这将从下拉列表中获取一个消毒值,以便在条件下使用我不确定如何动态创建named_scope链,因为我有5个人口统计学问题,并且可能其中一些将被设置为全部。

You can chain named scopes together: 您可以将命名范围链接在一起:

def index
  @results = Results.scoped
  @results = @results.gender(params[:gender]) unless params[:gender].blank?
  @results = @results.career(params[:career]) unless params[:career].blank?
end

I prefer however to use the has_scope gem: 但我更喜欢使用has_scope gem:

has_scope :gender
has_scope :career

def index
  @results = apply_scopes(Results).all
end

If you use has_scope with inherited_resources , you don't even need to define the index action. 如果将has_scopeinherited_resources 一起使用,则甚至不需要定义索引操作。

 named_scope :gender,lambda { |*args|
    unless args.first.blank?
      { :conditions => [ "gender = ?", args.first] }   
    end
  }

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. 如果你以这种方式编写命名范围,你可以将它们全部链接起来,如果你的一个参数将是空白的,则不会中断。

Result.gender("Male") will return male results.
Result.gender("") will return male and female too.

And you can chain all of your methods like this. 你可以像这样链接所有方法。 Finally as a filtering you can have like: 最后作为过滤你可以有:

Result.age(16).gender("male").career("beginer")
Result.age(nil).gender("").career("advanced") - will return results with advanced career, etc.

Try some like this: 试试这样的:

VistaFact.where( if active then {:field => :vista2} else {} end)

Or like this: 或者像这样:

VistaFact.where(!data.blank? ? {:field=>data.strip} : {}).where(some? ? {:field2 => :data2} : {}).where ...

That work for me very nice! 那对我来说非常好!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM