简体   繁体   中英

Ruby on rails form errors not displayed

I'm trying to display errors in my form but it not appearing, could someone help me on this ?

Here is my controller :

def create
 @bug = Bug.create(bug_params)

 redirect_to bugs_path
end

private

  def bug_params
    params.require(:bug).permit(:owner, :title, :description)
  end

My model :

class Bug < ApplicationRecord

    validates_presence_of :title
end

And my form :

<%= form_with model: @bug do |form| %>
    <% if @bug.errors.any? %>
        <h2>Errors : </h2>
        <ul>
            <% @bug.errors.full_messages.each do |message| %>
                <li><<%= message %>/li>
            <% end %>
        </ul>

    <% end %>

    <%= form.select :owner, @users.collect {|u| [ u.username, u.id ] } %>
    <%= form.text_field :title, placeholder: "title" %>
    <%= form.text_area :description, placeholder: "description" %>

    <%= form.submit %>
<% end %>

What's happening here is you are redirecting to bugs_path irrespective of the Bug being created or not. Instead, you should do something like this

@bug = Bug.new(bug_params)

if @bug.save
  redirect_to bugs_path, notice: 'Bug was successfully created.'
else
  render :new
end

Your markup has problems change this

<li><<%= message %>/li>

for

<li><%= message %></li>

Your controller create method need to modify for displaying error messages. Currently Your trying to create a Bug. If Bug created or not created then you redirected to bugs index page that's error object is resetting.

Here's the modified create method code -

def create
 @bug = Bug.create(bug_params)

 respond_to do |format|
   if @bug.persisted?
     format.html { redirect_to bugs_path, notice: 'Bug was successfully created.' }
   else
     format.html { render :new }
   end
 end
end

Hope it should work.

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