Foods
+There are no foods in your inventory.
+Food | +Measurement unit | +Unit Price | +Quantity | +Actions | +
---|
diff --git a/app/controllers/foods_controller.rb b/app/controllers/foods_controller.rb index 2c6a3ac..09b26f0 100644 --- a/app/controllers/foods_controller.rb +++ b/app/controllers/foods_controller.rb @@ -1,9 +1,10 @@ class FoodsController < ApplicationController + before_action :authenticate_user! before_action :set_food, only: %i[show edit update destroy] # GET /foods or /foods.json def index - @foods = Food.all + @foods = Food.where(user_id: current_user.id) end # GET /foods/1 or /foods/1.json @@ -20,10 +21,12 @@ def edit; end # POST /foods or /foods.json def create @food = Food.new(food_params) + @food.user = current_user respond_to do |format| if @food.save - format.html { redirect_to food_url(@food), notice: 'Food was successfully created.' } + flash[:success] = 'Food was successfully created.' + format.html { redirect_to foods_path } format.json { render :show, status: :created, location: @food } else format.html { render :new, status: :unprocessable_entity } @@ -50,7 +53,8 @@ def destroy @food.destroy! respond_to do |format| - format.html { redirect_to foods_url, notice: 'Food was successfully destroyed.' } + flash[:success] = 'Food was successfully destroyed.' + format.html { redirect_to foods_url } format.json { head :no_content } end end @@ -64,6 +68,6 @@ def set_food # Only allow a list of trusted parameters through. def food_params - params.require(:food).permit(:name, :measurement_unit, :price, :quantity, :user_id) + params.require(:food).permit(:name, :measurement_unit, :price, :quantity) end end diff --git a/app/models/food.rb b/app/models/food.rb index 9108308..283d309 100644 --- a/app/models/food.rb +++ b/app/models/food.rb @@ -2,4 +2,13 @@ class Food < ApplicationRecord belongs_to :user has_many :recipe_foods has_many :recipes, through: :recipe_foods + + validates :name, presence: true + validates :price, presence: true, numericality: { greater_than: 0 } + validates :measurement_unit, presence: true, inclusion: { in: %w[mg g kg l ml] } + validates :quantity, presence: true, numericality: { greater_than: 0 } + + def total_price + (price * quantity).round(2) + end end diff --git a/app/views/foods/_food.html.erb b/app/views/foods/_food.html.erb index 7f7d637..a2fc7e8 100644 --- a/app/views/foods/_food.html.erb +++ b/app/views/foods/_food.html.erb @@ -1,27 +1,9 @@ -
- Name: - <%= food.name %> -
- -- Measurement unit: - <%= food.measurement_unit %> -
- -- Price: - <%= food.price %> -
- -- Quantity: - <%= food.quantity %> -
- -- User: - <%= food.user_id %> -
- -<%= notice %>
+There are no foods in your inventory.
+Food | +Measurement unit | +Unit Price | +Quantity | +Actions | +
---|
<%= notice %>
-<%= alert %>
+