简体   繁体   English

Ruby on Rails表单错误未显示

[英]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. 这里发生的事情是,无论是否创建Bug,您都将重定向到bugs_path 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. 目前,您正在尝试创建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. 希望它能工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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