2

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.

4

3 回答 3

7

您可以将命名范围链接在一起:

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

但是,我更喜欢使用has_scope gem:

has_scope :gender
has_scope :career

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

如果您将has_scopeinherit_resources一起使用,您甚至不需要定义索引操作。

于 2010-05-12T02:18:43.883 回答
3
 named_scope :gender,lambda { |*args|
    unless args.first.blank?
      { :conditions => [ "gender = ?", args.first] }   
    end
  }

如果您以这种方式编写命名范围,则可以将所有它们链接起来,并且如果您的参数之一为空白,则不会中断。

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

你可以像这样链接你所有的方法。最后作为过滤,您可以拥有:

Result.age(16).gender("male").career("beginer")
Result.age(nil).gender("").career("advanced") - will return results with advanced career, etc.
于 2010-05-12T07:50:08.693 回答
0

试试这样的:

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

或者像这样:

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

这对我来说非常好!

于 2013-09-09T21:48:45.787 回答