parsley/app/controllers/logs_controller.rb
2018-04-13 10:25:18 -05:00

82 lines
1.8 KiB
Ruby

class LogsController < ApplicationController
before_action :ensure_valid_user
before_action :set_log, only: [:show, :update, :destroy]
before_action :require_recipe, only: [:new, :create]
def index
@logs = Log.for_user(current_user).order(:date).page(params[:page]).per(params[:per])
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
render json: { success: true }
else
render json: @log.errors, status: :unprocessable_entity
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]}]).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, :step_text, recipe_ingredients_attributes: [:name, :ingredient_id, :quantity, :units, :preparation, :sort_order, :id, :_destroy]])
end
end