简体   繁体   中英

Querying a model by a has many through association

I need to query my model by an associated model.

Pseudo code: @drinks = Drink.where(drink.ingredients ARE IN cabinet.ingredients)

Drink Model

class Drink < ActiveRecord::Base
  attr_accessible :name

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

Ingredient Model

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

User Model

class User < ActiveRecord::Base

  has_one :cabinet
end

Edit: As suggested I tried

Drink.joins(ingredients: :cabinet_ingredients)

However it returns multiple records of the same drink when I have one drink with 2 ingredients from my cabinet and/or multiple users.

I need to return only one record of the drink.. In addition, I need to only return a drink if all of its ingredients are matched in the cabinet

Here is how I would do it. Select a drink if all its ingredients are present in the given cabinet's ingredients. I know its not using Drink.where like your pseudo code but it would get the job done.

Drink.all.select{|drink| drink.ingredients.all?{|drink_ingredient| cabinet.ingredients.include?(drink_ingredient)}}

尝试这个。

Drink.joins(ingrediants: :cabinet_ingredients).uniq

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM