0
votes

Lets say I have recipes and ingredients, so there is a relation n:m.

Ok, there is everything ok and the relationship works and I have a join table named ingredients_recipe and its store recipe id and ingredient id for each recipe in the database.

Now, I want to create a search form where you can select ingredients and then it show recipes with thoses ingredients.

For example:

I select potato, tomato and rice, so it should show recipes with thoses ingredients.

1
So what is your problem now? - Hieu Pham
Check out this Railscast as well as this one. Post again when you have a specific programming issue. As it stands now, you're asking for a tutorial, which is outside the scope of Stack Overflow. - MarsAtomic

1 Answers

0
votes

Please find the following view as well as search code:

View:

  <%= form_tag (search_url) do %>
    <% @ingredients.each do |ing| %>
      <%= check_box_tag "ingredient_ids[]", ing.id, id: => "ingredient_ids_#{ing.id}" %>
    <% end %>
    <%= submit_tag "Search" %>
  <% end %>

Controller:

def search
  @recipes = Recipe.joins(:ingredients_recipes).where(
    ingredients_recipes: { ingredient_id: params[:ingredient_ids] } 
  )
end