From 9878b4265504d42c5aca94bd4f70762a8843f721 Mon Sep 17 00:00:00 2001 From: cryptogopher Date: Sun, 15 Sep 2019 19:00:04 +0200 Subject: [PATCH] Added Ingredient#destroy --- app/controllers/ingredients_controller.rb | 15 +++++++++++++++ app/models/ingredient.rb | 2 +- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/app/controllers/ingredients_controller.rb b/app/controllers/ingredients_controller.rb index 27f4f06..76efd38 100644 --- a/app/controllers/ingredients_controller.rb +++ b/app/controllers/ingredients_controller.rb @@ -1,5 +1,6 @@ class IngredientsController < ApplicationController before_action :find_project_by_project_id, only: [:index, :create] + before_action :find_ingredient, only: [:destroy] before_action :authorize def index @@ -20,6 +21,11 @@ class IngredientsController < ApplicationController end def destroy + # FIXME: don't destroy if any meal depend on ingredient + if @ingredient.destroy + flash[:notice] = 'Deleted ingredient' + end + redirect_to project_ingredients_url(@project) end private @@ -40,4 +46,13 @@ class IngredientsController < ApplicationController ] ) end + + # :find_* methods are called before :authorize, + # @project is required for :authorize to succeed + def find_ingredient + @ingredient = Ingredient.find(params[:id]) + @project = @ingredient.project + rescue ActiveRecord::RecordNotFound + render_404 + end end diff --git a/app/models/ingredient.rb b/app/models/ingredient.rb index cc93af1..a163d99 100644 --- a/app/models/ingredient.rb +++ b/app/models/ingredient.rb @@ -6,7 +6,7 @@ class Ingredient < ActiveRecord::Base belongs_to :project belongs_to :ref_unit, class_name: 'Unit' - has_many :nutrients, inverse_of: :ingredient + has_many :nutrients, inverse_of: :ingredient, dependent: :destroy accepts_nested_attributes_for :nutrients, allow_destroy: true, reject_if: proc { |attrs| attrs['quantity_id'].blank? && attrs['amount'].blank? }