Sage Harpuia
Sage Harpuia

Reputation: 356

How to use joins and where in ruby on rails?

Im having troubles with using .joins and .where

In my app the users can search for recipes using their ingredients as parameters.

For example, if you have rice and tomatoes, it will show you all recipes with rice and tomatoes (but if the recipe use a third ingredient it is not displayed).

Anyway, I have recipe and ingredient model and recipe model and a model for the join table called has_ingredient.

The model is basically something like this:

recipe --< has_ingredient >-- ingredient

Everything is working when I create recipes, it actually store the id of recipes and id of ingredients in the has_ingredient table.

anyway, for searching I created a separated model for it, I can actually select ingredients and send them to the controller via get method, but I having problems with this

@result=Recipe.joins(:has_ingredient).where(has_ingredient: {ing_id: params[:ingredients]})

I want to store in @result the list of recipes, but when I try to search i get the following error

Association named 'has_ingredient' was not found on Recipe; perhaps you misspelled it?

Im not sure what is the problem and Im having a hard time with RoR

Upvotes: 0

Views: 255

Answers (1)

IngoAlbers
IngoAlbers

Reputation: 5802

I think you should set it up like this:

class Recipe < ActiveRecord::Base
  has_many :recipe_ingredients
  has_many :ingredients, through: :recipe_ingredients
end

class Ingredient < ActiveRecord::Base
  has_many :recipe_ingredients
  has_many :recipes, through: :recipe_ingredients
end

Then RecipeIngredient would be the join model.

class RecipeIngredient < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :ingredient
end

You can read this great basics guide for more information on how to set everything up: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

If you set it up like this you can then use joins in the query like this:

@result = Recipe.joins(:ingredients).where(ingredients: { id: params[:ingredients] })

In the joins part of the query you have to use the association name and in the where clause you have to use the actual table name. (in this case it is both ingredients).

Using the association and table name might fix the problem for your current setup, even though I advise not to use the name has_ingredient for the model.

Upvotes: 1

Related Questions