我正在使用改革 gem来创建一个表单对象。通常在 rails 中:当表单上的验证失败时:field_with_errors
该类包装无效字段的标签和输入。这在我的改革表单对象中没有发生。
这是表单对象的类:
# app/forms/signup_form.rb
class SignupForm < Reform::Form
include Reform::Form::ActiveRecord
include Composition
model :user, on: :user
property :id, on: :user
property :name, on: :user
property :blog_id, on: :blog, from: :id
property :user_id, on: :blog
property :title, on: :blog
validates :name, presence: true
validates :title, presence: true
end
这是实际的形式:
# app/views/users/_form.html.erb
<%= form_for(signup_form, url: signup_form_path(signup_form.model[:user]), method: signup_form_method(signup_form.model[:user])) do |form| %>
<% if signup_form.errors.size > 0 %>
<div>
<p><%= pluralize(signup_form.errors.size, "error") %> prohibited the data from persisting</p>
<p>There were problems with the following fields:</p>
<ul>
<% signup_form.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= form.hidden_field(:user_id, value: form.object.user_id) %>
<div class="field">
<%= form.label :name, "* Name" %>
<%= form.text_field :name %>
</div>
<div class="field">
<%= form.label :title, "* Title" %>
<%= form.text_field :title %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
以下是提交之前表单的样子:
如果我单击Create User
按钮而不填写任何内容,则会失败,因为Name
andTitle
字段是必需的。它确实会失败,但无效的标签和字段没有被包裹,field_with_errors
因此没有使用 rails 默认样式设置field_with_errors
样式。它看起来像这样:
应用批准的答案以获得此问题的完整代码解决方案:
<div class="field <%= form_obj_field_with_errors(form.object.errors[:name].join(',')) %>">
<%= form.label :name, "* Name" %>
<%= form.text_field :name %>
</div>
<div class="field <%= form_obj_field_with_errors(form.object.errors[:title].join(',')) %>">
<%= form.label :title, "* Title" %>
<%= form.text_field :title %>
</div>
这是帮手:
def form_obj_field_with_errors(error_msg)
return unless error_msg.present?
return 'field_with_errors'
end
更新!!!
事实证明,上述解决方案是不必要的。改革确实适用field_with_errors
。我的错误是我在我的 rails 项目中使用了最新的、不稳定的改革版本。
之前我指定了这个 gem 来为我的 rails 项目带来改革:
gem 'reform-rails', '0.2.0rc1'
那个版本不稳定。我切换到最新的稳定版本,一切都按预期工作。无需field_with_errors
手动添加:
gem 'reform-rails', '~> 0.1.7'