ruby-on-rails – 如何使用Simple_form但没有模型显示验证错误消
发布时间:2020-12-17 03:17:23 所属栏目:百科 来源:网络整理
导读:我在Rails 4应用程序中使用Simple_form. 如何在与模型无关的视图中显示错误消息? 我希望得到与基于模型的其他视图相同的结果. 现在,这是视图中的代码: %= simple_form_for(:registration,html: { role: 'form' },:url = registrations_path) do |f| % %= f
我在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 %> 在“正常”视图(即,具有模型)中,行<%= f.error_notification%>显示错误. 我应该怎么做我的控制器初始化Simple_form使用的东西来显示错误? 谢谢 解决方法
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 然后你可以像这样在表单中添加错误(注意你指明是否通过设置’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,error: "This is an error on item2" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |