【问题标题】:How to use joins and where in ruby on rails?如何在 ruby​​ on rails 中使用连接和位置?
【发布时间】:2016-01-15 06:48:28
【问题描述】:

我在使用 .joins 和 .where 时遇到问题

在我的应用中,用户可以使用他们的成分作为参数来搜索食谱。

例如,如果您有米饭和西红柿,它会显示所有含有米饭和西红柿的食谱(但如果食谱使用第三种成分,则不会显示)。

无论如何,我有配方和成分模型、配方模型和一个名为 has_ingredient 的连接表模型。

模型基本上是这样的:

recipe --< has_ingredient >-- ingredient

当我创建食谱时一切正常,它实际上将食谱的 id 和成分的 id 存储在 has_ingredient 表中。

无论如何,为了搜索,我为它创建了一个单独的模型,我实际上可以选择成分并通过 get 方法将它们发送到控制器,但是我遇到了这个问题

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

我想在@result 中存储食谱列表,但是当我尝试搜索时出现以下错误

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

我不确定是什么问题,而且我很难使用 RoR

【问题讨论】:

  • has_ingredient是什么,如果是模型,名字应该是名词才能说清楚,顺便说一句,你的错误可能在has_ingredient,可能是has_ingredients

标签: ruby-on-rails ruby activerecord


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 2018-11-24
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多