Kaido
Kaido

Reputation: 127

Simple form error notification inside the form on validation

I have this form to create and update my product object, but i'm having problems to get the errors messages:

<%= simple_form_for @product do |f| %>
  <% if @product.errors.any? %>
    <div class="errors-container">
      <ul>
        <% @product.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
  <%= f.input :name, label: 'Product name' %>
  <%= f.input :description, label: 'Description' %>
  <%= f.association :category, label: 'Category' %>
  <%= f.input :price, label: 'Price' %>
  <%= f.input :picture %>
  <%= f.input :picture_cache, as: :hidden %>
  <%= f.button :submit %>
<% end %>

and these validations in my product model:

validates :name, :description, :category, :price, presence: true

this is my controller:

    class ProductsController < ApplicationController
  before_action :set_product, only: [:show, :edit, :update, :destroy]
  skip_before_action :authenticate_user!, only: [:index, :show]

  def index
  end


  def show
  end

  def new
    @product = Product.new
  end

  def edit
  end

  def create
    @product = current_user.products.new(product_params)
    if @product.save
      respond_to do |format|
        format.html { redirect_to products_path, notice: 'The product was successfully created.' }
      end
    else
      redirect_to new_product_path
    end
  end

  def update
    @product.update(product_params)
    respond_to do |format|
      format.html { redirect_to product_path, notice: 'The product was successfully updated.' }
    end
  end

  def destroy
    @product.destroy
    respond_to do |format|
      format.html { redirect_to products_path, notice: 'The product was successfully destroyed.' }
    end
  end

  private
    def set_product
      @product = Product.find(params[:id])
    end

    def product_params
      params.require(:product).permit(:name, :description, :category_id, :price, :picture, :picture_cache)
    end
  end

when i submit the form without any field required in the validation i don't get any error messages. Where am i doing wrong? UPDATE: I put my controller.

Upvotes: 0

Views: 635

Answers (1)

coreyward
coreyward

Reputation: 80128

Since you're redirecting when there's a validation error on create, @product is always going to be a new instance of Product that hasn't even had validations run.

Instead you want to render the new action view to show the form again, but without changing the page. This way @product gets passed to the view for the errors to be shown.

def create
  @product = current_user.products.new(product_params)
  if @product.save
    respond_to do |format|
      format.html { redirect_to products_path, notice: 'The product was successfully created.' }
    end
  else
    # changed the following line
    render :new
  end
end

Upvotes: 3

Related Questions