2017-08-22 1 views
0

Ich versuche, eine Möglichkeit zum Löschen von Zeilen aus der Tabelle, die mit einer anderen Tabelle zugeordnet ist.Wie autoclearing verbundenen Tabellenzeilen ohne gültige zugeordnete ID

Der Punkt ist, dass ich versuche, Anwendung für Rezepte zu erstellen. Und zum Beispiel möchte ich keine Situation haben, wenn 2 oder mehr Rezepte die gleiche Zutat haben (sagen wir Eier). Und wenn ich ein Rezept entferne, entfernt es automatisch den zugehörigen aktiven Datensatz, aber ich möchte es entfernen, wenn z. Eier werden nicht in einem anderen Rezept verwendet.

Ingredient Modell:

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

end 

Rezept Modell:

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 

So ist es eine Möglichkeit (ohne SQL-Abfragen) eine solche Operation durchzuführen?

Antwort

1

Beginnen Sie mit dem Erstellen einer Join-Tabelle, die Rezept und Zutat verbindet. Dies ist erforderlich, um eine Viele-zu-viele-Verknüpfung einzurichten.

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 

Sie können dann verwaiste Zeilen entfernen, indem Sie einen Rückruf zu erstellen:

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

scheint alles in Ordnung, aber wie beginer habe ich keine Ahnung, wie dies zu realisieren .... :( – MajQel

Verwandte Themen