ruby on rails - How to perform autoclearing associated table rows without valid associated id -




i trying find way clear rows table associated table.

the point trying create application recipes. , example don't want have situation when 2 or more recipes have same ingredient (let's eggs). , if remove 1 recipe remove automatically associated active record want remove when e.g. eggs won't used in recipe.

ingredient model:

class ingredient < applicationrecord   belongs_to :recipe, inverse_of: :ingredients  end 

recipe model:

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 there way (excluding sql queries) perform such operation?

start creating join table joins recipe , ingredient. required setup many many association.

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  # model master table ingredients  # using normalized table avoids duplication class ingredient < applicationrecord   has_many :recipe_ingredients   has_many :ingredients, through: :recipe_ingredients end  # contains quantity of ingredient used in recipe class recipeingredient < applicationrecord   belongs_to :recipe   belongs_to :ingredients end 

you can remove orphaned rows creating callback:

class recipeingredient < applicationrecord   belongs_to :recipe   belongs_to :ingredients    after_destroy |record|     ingredient = record.ingredient     unless ingredient.recipe_ingredients.any?       ingredient.destroy     end   end end 




wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -