如何使用Simple_form但没有模型显示验证错误消息?

Fre*_*rin 6 ruby-on-rails simple-form-for

我在Rails 4应用程序中使用Simple_form.

如何在与模型无关的视图中显示错误消息?

我希望得到与基于模型的其他视图相同的结果.

现在,这是视图中的代码:

<%= simple_form_for(:registration, html: { role: 'form' }, :url => registrations_path) do |f| %>

  <%= f.error_notification %>

  <%= f.input :name, :required => true, :autofocus => true %>
  <%= f.input :email, :required => true %>
  <%= f.input :password, :required => true %>
  <%= f.input :password_confirmation, :required => true %>

  <%= f.button :submit %>

<% end %>
Run Code Online (Sandbox Code Playgroud)

在"正常"视图中(即使用模型),行<%= f.error_notification %>显示错误.

我应该怎么做我的控制器初始化Simple_form使用的东西来显示错误?

谢谢

小智 5

Simple Form不支持​​"开箱即用"的此功能.但你可以在这样的初始化器中添加一个"猴子补丁"(免责声明 - 这似乎适用于我的简单测试用例但尚未经过彻底测试):

// Put this code in an initializer, perhaps at the top of initializers/simple_form.rb
module SimpleForm
  module Components
    module Errors
      def has_errors?
        has_custom_error? || (object && object.respond_to?(:errors) && errors.present?)
      end

      def errors
        @errors ||= has_custom_error? ? [options[:error]] : (errors_on_attribute + errors_on_association).compact
      end
    end
  end
end

module SimpleForm
  class ErrorNotification
    def has_errors?
      @options[:errors] || (object && object.respond_to?(:errors) && errors.present?)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样在表单中添加错误(注意你指明是否通过设置'errors:true'来显示错误通知,你必须执行自己的检查以确定是否存在错误,并动态添加错误):

=simple_form_for :your_symbol do |f|
  =f.error_notification errors: true
  =f.input :item1, as: :string, error: "This is an error on item1"
  =f.input :item2, as: :string, error: "This is an error on item2"
Run Code Online (Sandbox Code Playgroud)


pdo*_*obb 0

助手simple_form_for必须包装一个模型。但仅仅因为我们这么说并不意味着它必须是由数据库表支持的 ActiveRecord 模型。您可以自由创建不受数据库支持的模型。在 Rails 3+ 中,执行此操作的方法是让您的类包含您需要的组件ActiveModel这篇文章通过一个例子解释了如何做到这一点(我确信还有很多其他例子)。一旦您拥有了一个模型,ActiveModel::Validation您可以将其添加到errors集合中,然后该f.error_notification语句将输出错误,就像您在表支持模型中所习惯的那样。

TL;DR:创建一个非 ActiveRecord、非表支持的模型,然后将其视为常规旧模型,并且表单应该做正确的事情。