class RecipesController < ApplicationController before_action :set_recipe, only: [:show, :edit, :update, :destroy] before_action :ensure_valid_user, except: [:show, :scale, :index] # GET /recipes def index @criteria = ViewModels::RecipeCriteria.new(params[:criteria]) @criteria.page = params[:page] @criteria.per = params[:per] @recipes = Recipe.for_criteria(@criteria).includes(:tags) end # GET /recipes/1 # GET /recipes/1.json def show if params[:scale].present? @scale = params[:scale] @recipe.scale(params[:scale], true) end if params[:system].present? @system = params[:system] case @system when 'metric' @recipe.convert_to_metric when 'standard' @recipe.convert_to_standard end end if params[:unit].present? @unit = params[:unit] case @unit when 'mass' @recipe.convert_to_mass when 'volume' @recipe.convert_to_volume end end @recipe = RecipeDecorator.decorate(@recipe, view_context) end # GET /recipes/1 def scale @scale = params[:factor] @recipe.scale(@scale, true) @recipe = RecipeDecorator.decorate(@recipe, view_context) render :show end # GET /recipes/new def new @recipe = Recipe.new end # GET /recipes/1/edit def edit ensure_owner @recipe end # POST /recipes def create @recipe = Recipe.new(recipe_params) @recipe.user = current_user if @recipe.save redirect_to @recipe, notice: 'Recipe was successfully created.' else render :new end end # PATCH/PUT /recipes/1 def update ensure_owner(@recipe) do if @recipe.update(recipe_params) redirect_to @recipe, notice: 'Recipe was successfully updated.' else render :edit end end end # DELETE /recipes/1 def destroy ensure_owner(@recipe) do @recipe.deleted = true if @recipe.save(validate: false) redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' else redirect_to recipes_url, error: 'Recipe could not be destroyed.' end end end private # Use callbacks to share common setup or constraints between actions. def set_recipe @recipe = Recipe.includes(recipe_ingredients: {ingredient: :ingredient_units }).find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def recipe_params params.require(:recipe).permit(:name, :description, :source, :yields, :total_time, :active_time, tag_names: [], recipe_ingredients_attributes: [:name, :ingredient_id, :quantity, :units, :preparation, :sort_order, :id, :_destroy], recipe_steps_attributes: [:step, :sort_order, :id, :_destroy]) end end