How to use joins and where in ruby on rails?

时间:2016-01-15 06:48:28

标签: ruby-on-rails ruby activerecord

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

1 个答案:

答案 0 :(得分:1)

我认为你应该这样设置:

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

然后RecipeIngredient将成为连接模型。

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

您可以阅读这篇精彩的基础知识指南,了解有关如何设置所有内容的更多信息: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

如果你这样设置,你可以在查询中使用连接,如下所示:

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

在查询的joins部分中,您必须使用关联名称,在where子句中,您必须使用实际的表名。 (在这种情况下,它都是ingredients)。

使用关联和表名可能会解决当前设置的问题,即使我建议不要为模型使用名称has_ingredient