Rails 3 ActiveRecord: "OR-ing" together multiple bools
I have an ActiveRecord object RaceCarDriver
. Three of the fields are boolean: is_from_texas
, is_from_arkansas
, and is_from_indiana
. In the user search interface, the user could select neither to see all results, select is_from_texas
to see only drivers from Texas, or select is_from_texas
and is_from_indiana
to see all drivers from one of those states.
Now, I know this example is a bit contrived, but I wanted to avoid the complexity of the actual app.
My best attempt is along these lines:
@drivers = RaceCarDriver.select('name').
where(params[:check_texas] == 0 || :is_from_texas => params[:check_texas]).
where(params[:check_arkansas] == 0 || :is_from_arkansas => params[:check_arkansas]).
where(params[:check_indiana] == 0 || :is_from_indiana => params[:check_indiana])
However, this ANDS
the chained where
clauses together, making it so that if Texas and Indiana were both checked a driver would have to be from both states.
Again, 开发者_Go百科I know this is contrived. Any help is appreciated.
RaceCarDriver.select('name').
where("is_from_texas = ? OR is_from_arkansas = ? OR is_from_indiana = ?",params[:is_from_texas],params[:is_from_arkansas],params[:is_from_indiana])
@drivers = RaceCarDriver.select('name')
@drivers = @drivers.where(:is_from_texas => params[:check_texas]) if params[:check_texas]
@drivers = @drivers.where(:is_from_arkansas => params[:check_arkansas]) if params[:check_arkansas]
@drivers = @drivers.where(:is_from_indiana => params[:check_indiana]) if params[:check_indiana]
EDIT
Solution 1:
where_options = { :is_from_texas => params[:check_texas],
:is_from_arkansas => params[:check_arkansas],
:is_from_indiana => params[:check_indiana] }.select{|k,v| v.present? }
where_conditions = where_options.map{|k,v| "#{k} = #{v}"}.join(" OR ")
@drivers = RaceCarDriver.select('name').where(where_conditions)
Solution 2:
@scoped_drivers = RaceCarDriver.select('name')
@drivers = []
@drivers << @scoped_drivers.where(:is_from_texas => params[:check_texas]) if params[:check_texas]
@drivers << @scoped_drivers.where(:is_from_arkansas => params[:check_arkansas]) if params[:check_arkansas]
@drivers << @scoped_drivers.where(:is_from_indiana => params[:check_indiana]) if params[:check_indiana]
@drivers.flatten!
精彩评论