错误消息未在Rails

时间:2015-06-01 23:11:02

标签: ruby-on-rails ruby

    else
      object      = record.is_a?(Array) ? record.last : record
      raise ArgumentError, "First argument in form cannot contain nil or be empty" unless object
      object_name = options[:as] || model_name_from_record_or_class(object).param_key
      apply_form_for_options!(record, object, options)
    end

嗨,Rails和编程相对较新。当我尝试提交包含错误的表单时,我收到此错误。当正确填写所有字段时,它工作得非常好,但如果某个表单缺少某些内容,则不会像在此图片中那样显示错误:

enter image description here

相反,我明白了:

enter image description here

以下是表单的代码:

<%= form_for(@quote) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
    <div class="field">
    <%= f.text_area :content, placeholder: "Save a new quote..." %>
    <%= f.text_field :author, placeholder: "Author:" %>
    <%= f.text_field :source, placeholder: "Source:" %>
    </div>
  <%= f.submit "Save", class: "btn btn-primary" %>
<% end %>

以下是错误消息的代码:

<% if object.errors.any? %>
 <div id="error_explanation">
  <div class="alert alert-danger">
   The form contains <%= pluralize(object.errors.count, "error") %>.
  </div>
  <ul>
<% object.errors.full_messages.each do |msg| %>
  <li><%= msg %></li>
<% end %>
  </ul>
 </div>
   

这是QuotesController的代码:

 class QuotesController < ApplicationController
 before_action :logged_in_user, only: [:create, :destroy]

 def create
  @quote = current_user.quotes.build(quote_params)
   if @quote.save
    flash[:success] = "Quote saved!"
    redirect_to root_url
   else
    render 'static_pages/home'
   end
 end

def edit
end

def destroy
end

private

 def quote_params
  params.require(:quote).permit(:content, :author, :source)
 end
end

如何修复它以便像第一张图片一样正确渲染错误?

*事实证明代码实际上正在运行,但唯一的问题是我网站的主页运行两个调用shared / error_messages的表单,这就是为什么我猜它们会发生冲突。当我删除其中一个表单时,另一个表单工作正常。关于如何在同一页面上运行两个表单的任何想法? *

0 个答案:

没有答案