Nicholas Haley
Nicholas Haley

Reputation: 4024

Searching for records that match multiple search queries with Ransack

I am building a recipe search that I would to return records that match multiple ingredient queries. For example, if I input "Chicken" and "Carrots", my results should only return recipes that contain Chicken and Carrots.

So far I've got the search working well with just one query. Unfortunately I can't find anywhere in the Ransack documentation how to go about searching with multiple queries.

def index
if params[:query]
  @q = Recipe.ransack(ingredients_name_cont: params[:query])
  @recipes = @q.result(distinct: true)
else
  @recipes = Recipe.all
end

render json: @recipes
end

Any ideas? Thanks!

EDIT: To add to the description above, I am using Rails as my API. I will not be building templates in Rails and so can't make use of any form helpers.

EDIT 2: Looking at the docs more closely (https://github.com/activerecord-hackery/ransack/wiki/basic-searching), it seems like cont_any is very close to what I need, except instead of returning records that match one or the other, I need to return records that match BOTH. Ideas?

Upvotes: 1

Views: 1855

Answers (1)

bo-oz
bo-oz

Reputation: 2872

You should do the searching in controller like this:

  def search
    @q = Recipe.ransack(params[:q])
    @recipes = @q.result(distinct: true).published.include_related_models
  end

And build your search form like this (in HAML in my case):

.container
  %h3 Zoek recepten
  = search_form_for @q, url: search_recipes_path do |f|
    .input-group
      = f.search_field :title_cont, class: 'form-control', placeholder: 'Uw zoekterm'

For a nested relationship I'm using something like this:

= f.collection_select(:recipe_categorizations_recipe_category_id_in, RecipeCategory.all, :id, :name,{}, {multiple: true, class: 'chosen-select form-control'})

This is for searching the RecipeCategorization model for recipe_category_id (which relates to RecipeCategory)

UPDATE: This is how my params[:q] looks like. Probably need to address the correct relationships in the parameter names:

{"title_cont"=>"name", "recipe_categorizations_recipe_category_id_in"=>["", "4"], "ingredients_item_id_in_all"=>["", "2"], "steps_technique_id_in"=>["", "2"], "difficulty_in"=>"1"} 

Upvotes: 1

Related Questions