简体   繁体   中英

Ruby on Rails form errors not displaying

I am creating a basic app to create and store recipes to practice and can't seem to display errors under my forms, simple example of what I have below -

recipes_controller.rb (relevant sections )

def new
  @recipe = Recipe.new
end

def create
  @recipe = Recipe.new(recipe_params)
  @recipe.save
  redirect_to '/create_recipe'
end

private  
def recipe_params
  params.require(:recipe).permit(:title, :description)
end

recipe.rb(model)

class Recipe < ApplicationRecord
    has_many :ingredients
    has_many :steps

    validates_presence_of :title
end

new.html.erb

<%= form_for @recipe do |f| %>
    <div class="new_recipe_form">

      <% if @recipe.errors.any? %>
        <div class="form_error">
          <ul>
            <% @recipe.errors.full_messages.each do |msg| %>
              <li><%='Error: ' +  msg %></li>
            <% end %>
          </ul>
        </div>
      <% end %>

      <%= f.label :title %>
      <%= f.text_field :title %>

      <%= f.label :description %>
      <%= f.text_area :description %>

    </div>

    <div>
      <%= f.submit %>
    </div>
<% end %>

When I submit the form with no title, nothing happens. It doesn't create the recipe so I know the validator is working but no error appears.

Any help would be much appreciated.

You are redirecting user to new action no matter if the recipe has been created or not. After redirect the new action is executed and @recipe = Recipe.new sets @recipe to new object that does not contain any pieces of information about recipe user was trying to create before (nor validation errors). What you should do is render new action inside create action instead of redirecting. Something like this could help:

def create
  @recipe = Recipe.new(recipe_params)
  if @recipe.save
    redirect_to @recipe
  else
    render :new
  end
end

(I assumed you have show action in your controller and redirected user to show action after successful creation. If this is not a proper behaviour just change redirect_to @recipe to whatever you want)

P. Boro got it but I think they got the if and else the wrong way around, my controller now looks like this and it's working!

def create
  @recipe = Recipe.new(recipe_params)
  if @recipe.save
    redirect_to @recipe
  else
    render :new
  end
end

Thank you

Good to hear you got the solutions.

But you are brand new to Ruby and Rails so What I would like to suggest you, first go through scaffold generator so that you will get the basic idea of MVC and How CRUD operation works in rails?

After generating code with scaffold explore it deeply.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM