Reputation: 2464
I have these two inputs:
<%= search_form_for @search, url: search_path, method: :post do |f| %>
<%= f.text_field :thing_false %>
<%= f.text_field :thing_null %>
<% end %>
and when they're both set to "t", I get this query executed:
SQL: SELECT "stuffs".* FROM "stuffs" WHERE (("stuffs"."thing" = 'f' AND "stuffs"."thing" IS NULL))
How do I make it so I get this executed?
SQL: SELECT "stuffs".* FROM "stuffs" WHERE (("stuffs"."thing" = 'f' OR "stuffs"."thing" IS NULL))
The ransack documentation doesn't really address this. This is the closest example that I can find:
>> User.search(:first_name_or_last_name_cont => "Rya").result.to_sql
=> SELECT "users".* FROM "users" WHERE ("users"."first_name" LIKE '%Rya%'
OR "users"."last_name" LIKE '%Rya%')
Upvotes: 2
Views: 2454
Reputation: 6899
If you don't want the user to have to select the "any" option, you can make it so that the search always uses "OR" by adding something like this in your controller:
@search = User.search(params[:q])
@search.combinator = "or"
@users = @search.result
You can also create different groupings of search fields and specify the appropriate combination within the grouping. The controller could have something like:
@search = User.search(params[:q])
(0..1).each do |index|
@search.build_grouping unless @search.groupings[index]
@search.groupings[index].combinator = "or"
end
@users = @search.result
And the view could have something like:
<%= search_form_for @search do |f| %>
<% @search.groupings.each.with_index do |grouping,index| %>
<%= f.grouping_fields grouping do |g| %>
<% if index == 0 %>
<%#= fields for first grouping here %>
<% end %>
<% if index == 1 %>
<%#= fields for second grouping here %>
<% end %>
<% end %>
<% end %>
<%= f.submit "Search" %>
<% end %>
The RansackDemo page is a good place to play around with the different search options. There is a Simple Mode and an Advanced Mode. The source code is available on github and the views there give some indication of how to put together the groupings and conditions.
Additional info is also available in RailsCast 370.
Upvotes: 6
Reputation: 2464
throw this under your search_form_for tag. This is assuming that you're using f:
<%= f.combinator_select %>
it'll generate a select with two options. ALL or ANY. ANY will use an OR clause. ALL will use an AND clause.
Upvotes: 0