Rails 4 collection_check_boxes 表单刷新后持续存在

Rails 4 collection_check_boxes persistent after form refresh

我在表单中使用 Rails 4 collection_check_boxes。填写表格时,我选中了一些复选框。我注意到当表单在验证错误后刷新时,选中的复选框仍然存在。这是标签的功能吗?我在文档中找不到此信息。

复选框表单字段代码:

<div class="field">
  <%= f.label "Area of Interest" %><br />
  <%= f.collection_check_boxes :interest_ids, Interest.all, :id, :name do |b| %>
    <div class="collection-check-box">
      <%= b.check_box %>
      <%= b.label %>
    </div>
  <% end %>
</div>

我确实希望复选框在表单刷新后保持选中状态,但我想确保它是一项功能,而不仅仅是巧合,它对我有用。

任何信息都会有帮助,谢谢!

我认为验证失败页面刷新与 'form refresh' 的操作不同,除非您在控制器中添加了在表单保存失败时会重置表单的语言。

当您检查 interest_ids 表单并点击 'submit' 时,它会将任何通过验证的检查值添加到您的模型中作为已保存的 :interest_id 值,因此保存的值是是什么让复选框持续存在,即使整个表单验证失败。

如果您希望在表单的任何部分验证失败时重置您的表单,我建议您在创建操作的控制器中添加一个 if/else 语句。 @object.interest_ids = [] 会将对象上存储的 interest_ids 重置为空数组,这将取消选中复选框。

def create
  @object = Object.new
  if @object.save
    redirect_to object_path(@object)
  else
    @object.interest_ids = []
    render :new
  end
end

只要您使用 render :action 而不是 redirect_to :action 在失败时呈现您的表单,这就是标签的一个功能 save/validation:

def create
  @user = User.create(user_params)
  if @user.valid?
    redirect_to action: :show
  else
    render :new # @user gets passed to form_for
  end
end

主要区别在于,当您使用 render :new 时,您的创建操作中的 @user 模型实例会传递到您的表单。

现在,在 new.html.erb 视图中:

form_for @user do |f|
  # Fields using the syntax f.text_field :attr_name, `f.collection_check_boxes :attr_name`, etc will reference the :attr_name in both @user to populate the value(s). Also, @user.errors[:attr_name] to show an error message, if present.
end

基本上,发生的事情是在您的控制器中调用模型上的 savecreatevalidatevalid? 之一。调用这些方法之一后验证失败会阻止保存到数据库,但失败的值仍然存在于 @user 对象中。此外,errors 对象现在填充了有关哪些属性更新失败以及验证失败的原因的信息。

因此,当您重新呈现表单时,您会看到复选框仍处于选中状态,因为它们是根据模型实例本身的值填充的。同样,任何具有匹配错误的字段也应该显示该字段的错误。