class LogsController < ApplicationController before_action :ensure_valid_user before_action :set_log, only: [:show, :edit, :update, :destroy] before_action :set_recipe, only: [:new, :create] before_action :require_recipe, only: [:new, :create] def index @logs = Log.for_user(current_user).order(:date) end def show ensure_owner(@log) end def edit ensure_owner(@log) end def update ensure_owner(@log) do if @log.update(log_params) redirect_to logs_path, notice: 'Log Entry was successfully updated.' else render :edit end end end def new @log = Log.new @log.date = Time.now @log.user = current_user @log.source_recipe = @recipe @log.recipe = @recipe.log_copy(current_user) end def create @log = Log.new @log.assign_attributes(log_params) @log.recipe.is_log = true @log.recipe.user = current_user @log.user = current_user @log.source_recipe = @recipe if @log.save redirect_to logs_path, notice: 'Log Entry was successfully created.' else render :new end end def destroy ensure_owner(@log) do @log.destroy redirect_to logs_url, notice: 'Log Entry was successfully destroyed.' end end private def set_log @log = Log.find(params[:id]) end def set_recipe if params[:recipe_id].present? @recipe = Recipe.includes([{recipe_ingredients: [:ingredient]}, :recipe_steps]).find(params[:recipe_id]) end end def require_recipe unless @recipe raise ActiveRecord::RecordNotFound end end def log_params params.require(:log).permit(:date, :rating, :notes, recipe_attributes: [:name, :description, :source, :yields, :total_time, :active_time, recipe_ingredients_attributes: [:name, :ingredient_id, :quantity, :units, :preparation, :sort_order, :id, :_destroy], recipe_steps_attributes: [:step, :sort_order, :id, :_destroy]]) end end