【问题标题】:Rails 4 collection_check_boxes persistent after form refresh表单刷新后Rails 4 collection_check_boxes持久化
【发布时间】:2016-08-30 08:51:40
【问题描述】:

我在表单中使用 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>

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

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

【问题讨论】:

    标签: ruby-on-rails forms ruby-on-rails-4 checkbox checked


    【解决方案1】:

    只要您使用render :action 而不是redirect_to :action 在保存/验证失败时呈现您的表单,它就是标签的一个功能:

    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 时,您的 create 操作中的 @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 对象现在填充了有关哪些属性未能更新以及验证失败的原因的信息。

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

    【讨论】:

      【解决方案2】:

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

      当您检查表单的interest_ids 并点击“提交”时,它会将任何通过验证的检查值添加到您的模型中作为保存的 :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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-09-22
        • 2011-11-06
        • 1970-01-01
        • 1970-01-01
        • 2011-12-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多