2017-08-22 7 views
0

J'essaie de trouver un moyen d'effacer les lignes de la table qui est associée à une autre table.Comment effectuer l'autoclairage des lignes de table associées sans ID associé valide

Le point est que j'essaye de créer l'application pour des recettes. Et par exemple je ne veux pas avoir de situation quand 2 ou plusieurs recettes ont le même ingrédient (disons des oeufs). Et si j'enlève une recette, elle enlèvera automatiquement le dossier actif associé, mais je veux l'enlever quand par exemple. les œufs ne seront pas utilisés dans une autre recette.

Modèle Ingrédients:

class Ingredient < ApplicationRecord 
    belongs_to :recipe, inverse_of: :ingredients 

end 

Recette Modèle:

class Recipe < ApplicationRecord 
    has_many :ingredients, inverse_of: :recipe 
    has_many :directions, inverse_of: :recipe 

    accepts_nested_attributes_for :ingredients, 
            reject_if: proc { |attributes| attributes['name'].blank? }, 
            allow_destroy: true 
    accepts_nested_attributes_for :directions, 
            reject_if: proc { |attributes| attributes['step'].blank? }, 
            allow_destroy: true 

    validates :tittle, :description, :image, presence: true 
    has_attached_file :image, styles: { :medium => "400x400#" } 
    validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/ 
end 

Ainsi est-il possible (à l'exception des requêtes SQL) pour effectuer une telle opération?

Répondre

1

Commencez par créer une table de jointure qui joint Recipe et Ingredient. Ceci est nécessaire pour configurer une association plusieurs à plusieurs.

class Recipe < ApplicationRecord 
    has_many :recipe_ingredients 
    has_many :ingredients, through: :recipe_ingredients 

    accepts_nested_attributes_for :ingredients, 
    reject_if: proc { |attributes| attributes['name'].blank? }, 
    allow_destroy: true 

    # ... 
end 

# This model is the master table for ingredients 
# using a normalized table avoids duplication 
class Ingredient < ApplicationRecord 
    has_many :recipe_ingredients 
    has_many :ingredients, through: :recipe_ingredients 
end 

# This contains the quantity of an ingredient used in a recipe 
class RecipeIngredient < ApplicationRecord 
    belongs_to :recipe 
    belongs_to :ingredients 
end 

Vous pouvez ensuite supprimer des lignes orphelins en créant un rappel:

class RecipeIngredient < ApplicationRecord 
    belongs_to :recipe 
    belongs_to :ingredients 

    after_destroy do |record| 
    ingredient = record.ingredient 
    unless ingredient.recipe_ingredients.any? 
     ingredient.destroy 
    end 
    end 
end 
+0

tout semble bien, mais comme beginer je ne sais pas comment mettre en œuvre cette .... :( – MajQel