2017-08-22 17 views
0

別のテーブルに関連付けられているテーブルから行を消去する方法を見つけようとしています。関連付けられたテーブルの行を有効な関連IDなしで自動切断する方法

要は、レシピ用のアプリケーションを作成しようとしていることです。 例えば、2つ以上のレシピが同じ成分を持っている場合(私は卵と言う)、状況を持ちたくないです。 1つのレシピを削除すると、関連付けられたアクティブレコードは自動的に削除されますが、削除する必要があります。卵は別のレシピでは使用されません。

成分モデル:

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クエリを除く)はありますか?

答えて

1

まず、レシピと成分を結合する結合テーブルを作成します。これは、多対多関連を設定するために必要です。

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 
+0

をすべての罰金だが、beginerとして、私は....これを実装する方法が分からない:( – MajQel

関連する問題