0

我需要通过关联模型查询我的模型。

伪代码:@drinks = Drink.where(drink.ingredients ARE IN cabinet.ingredients)

饮料模型

class Drink < ActiveRecord::Base
  attr_accessible :name

  has_many :recipe_steps, :dependent => :destroy
  has_many :ingredients, through: :recipe_steps
end

成分模型

class Ingredient < ActiveRecord::Base
  attr_accessible :name

  has_many :recipe_steps
  has_many :drinks, through: :recipe_steps
  has_many :cabinet_ingredients
  belongs_to :cabinet
end

用户模型

class User < ActiveRecord::Base

  has_one :cabinet
end

编辑:正如我所建议的那样

Drink.joins(ingredients: :cabinet_ingredients)

但是,当我从我的柜子和/或多个用户中喝一种含有 2 种成分的饮料时,它会返回同一种饮料的多条记录。

我只需要退回一份饮料的记录。另外,我只需要退回所有成分在柜子中匹配的饮料

4

2 回答 2

1

这是我将如何做到的。如果所有成分都存在于给定橱柜的成分中,则选择一种饮料。我知道它Drink.where不像你的伪代码那样使用,但它会完成工作。

Drink.all.select{|drink| drink.ingredients.all?{|drink_ingredient| cabinet.ingredients.include?(drink_ingredient)}}
于 2013-02-23T02:13:40.863 回答
0

试试这个。

Drink.joins(ingrediants: :cabinet_ingredients).uniq
于 2013-02-22T22:55:44.837 回答