【问题标题】:Instead of show a notice error, show the error in the input不是显示通知错误,而是在输入中显示错误
【发布时间】:2014-09-11 20:05:43
【问题描述】:

我有一个带有 Twitter Bootstrap 的 rails 应用程序,当验证一个对象(如名称,并且名称为空白)时,我收到一个错误,但在闪存/通知中,如下图所示:

好的,但是,我希望错误显示在输入中,并且输入的类是 .has-error(或类似的东西)。我查看了 field_error_proc 并尝试更改它,但未成功。

【问题讨论】:

  • 您可以在views/layout/application.html.erb中的<%= yield %>之后添加<%= debug(params) if Rails.env.development? %>。它将显示表单传递给控制器​​的参数的详细信息
  • 我强制显示这个错误。我真正想要的是在输入中显示错误,而不是在通知/弹出窗口中。

标签: ruby-on-rails twitter-bootstrap ruby-on-rails-4


【解决方案1】:

我们以前做过(你可以在http://firststopcosmeticshop.co.uk看到 - 点击“注册”)

--

错误

我们这样做的方式是use the following

#app/views/users/new.html.erb
<%= form_for @user do |f| %>

   <%= f.text_field :your_param %>
   <%= @user.errors[:your_param].first if @user.errors[:your_param].present? %>

   <%= f.submit %>
<% end %>

您需要考虑的其他一点是,Rails 会自动将field_with_errors 类附加到任何有错误的输入。如果您想为充满错误的输入设置样式,您可以使用附加答案中的样式建议

【讨论】:

  • 好的。这对我有用,但在我的情况下,field_with_erros 类没有附加到输入中并出现错误。我不知道这是宝石的特殊性还是什么。我知道我可以使用 jQuery 来做到这一点.. 但是.. 你知道,它就像每个控件/视图的一行 js。
【解决方案2】:

我在我的项目中将 field_error_proc 设置为打击,它工作正常

config.action_view.field_error_proc = Proc.new do |html_tag, instance|
  case instance
  when ::ActionView::Helpers::Tags::Label
    html_tag
  else
    error_message = instance.error_message.is_a?(Array) ?
      instance.error_message.join(', ') :
      instance.error_message

    %Q(<div class="has-error">#{html_tag}<div class='help-block'>#{error_message}</div></div>).html_safe
  end
end

【讨论】:

    猜你喜欢
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 2021-11-24
    • 2022-11-17
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多