parsley/app/controllers/logs_controller.rb

86 lines
2.1 KiB
Ruby
Raw Normal View History

2016-07-06 21:00:35 -05:00
class LogsController < ApplicationController
2016-07-27 22:30:57 -05:00
before_action :ensure_valid_user
2018-04-13 10:25:18 -05:00
before_action :set_log, only: [:show, :update, :destroy]
2018-04-13 23:32:34 -05:00
before_action :set_recipe, only: [:new, :create]
2016-07-06 21:00:35 -05:00
before_action :require_recipe, only: [:new, :create]
def index
2018-04-13 23:32:34 -05:00
@logs = Log.for_user(current_user).order(date: :desc).page(params[:page]).per(params[:per])
2020-08-07 12:33:06 -05:00
render json: LogSummarySerializer.for(@logs, collection_name: 'logs')
2016-07-06 21:00:35 -05:00
end
def show
ensure_owner(@log)
2020-08-07 12:33:06 -05:00
render json: LogSerializer.for(@log)
2016-07-06 21:00:35 -05:00
end
def edit
ensure_owner(@log)
2020-08-07 12:33:06 -05:00
render json: LogSerializer.for(@log)
2016-07-06 21:00:35 -05:00
end
def update
ensure_owner(@log) do
if @log.update(log_params)
2018-04-15 14:15:42 -05:00
render json: { success: true }
2016-07-06 21:00:35 -05:00
else
2018-04-15 14:15:42 -05:00
render json: @log.errors, status: :unprocessable_entity
2016-07-06 21:00:35 -05:00
end
end
end
def new
@log = Log.new
2016-08-12 16:05:24 -05:00
@log.date = Time.now
2016-07-27 22:30:57 -05:00
@log.user = current_user
@log.source_recipe = @recipe
@log.recipe = @recipe.log_copy(current_user)
2016-07-06 21:00:35 -05:00
end
def create
2016-07-27 22:30:57 -05:00
@log = Log.new
@log.assign_attributes(log_params)
2016-08-15 17:43:02 -05:00
@log.recipe.is_log = true
@log.recipe.user = current_user
2016-07-06 21:00:35 -05:00
@log.user = current_user
2016-07-27 22:30:57 -05:00
@log.source_recipe = @recipe
2016-07-06 21:00:35 -05:00
if @log.save
2018-04-13 10:25:18 -05:00
render json: { success: true }
2016-07-06 21:00:35 -05:00
else
2018-04-13 10:25:18 -05:00
render json: @log.errors, status: :unprocessable_entity
2016-07-06 21:00:35 -05:00
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
2018-09-12 17:17:15 -05:00
@log = Log.includes({recipe: {recipe_ingredients: {food: :food_units} }}).find(params[:id])
2016-07-06 21:00:35 -05:00
end
def set_recipe
if params[:recipe_id].present?
2018-09-12 17:17:15 -05:00
@recipe = Recipe.includes([{recipe_ingredients: [:food]}]).find(params[:recipe_id])
2016-07-06 21:00:35 -05:00
end
end
2016-07-27 22:30:57 -05:00
def require_recipe
2016-07-06 21:00:35 -05:00
unless @recipe
raise ActiveRecord::RecordNotFound
end
end
def log_params
2017-04-14 16:40:38 -05:00
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]])
2016-07-06 21:00:35 -05:00
end
end