簡體   English   中英

如何在沒有有效關聯ID的情況下自動清除關聯表行

[英]How to perform autoclearing associated table rows without valid associated id

我試圖找到一種方法來清除與另一個表關聯的表中的行。

關鍵是我正在嘗試為食譜創建應用程序。 例如,當兩個或兩個以上的食譜具有相同的成分(比如雞蛋)時,我不想出現這種情況。 如果我刪除一個食譜,它將自動刪除關聯的活動記錄,但是當例如雞蛋將不會用於另一個食譜時,我想刪除它。

成分模型:

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

end

配方型號:

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

那么,有什么方法(不包括sql查詢)執行這種操作?

首先創建一個聯接配方和成分的聯接表。 這是建立多對多關聯所必需的。

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

然后,您可以通過創建回調來刪除孤立的行:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM