2016-05-04 35 views
1

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

复选框表单域代码:

<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> 

我想复选框留形式刷新后检查,但希望确保它是一个功能,而不是只是一个巧合,是不是为我工作。

的任何信息将是有益的,谢谢!

回答

0

这是标签的功能,只要你使用的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时,您创建操作中的@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 

基本上,发生的事情是在你的控制你调用模型的save之一,createvalidate,或valid?。在调用其中一种方法之后验证失败会阻止保存到数据库,但失败的值仍存在于@user对象中。此外,现在将填充关于哪些属性未能更新的信息以及验证失败的原因的errors对象。

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

0

我不认为验证失败页面刷新是同样的动作为“形式刷新”,除非你加入你的控制器语言如果表单无法保存,将重置您的形式。

当您检查interest_ids表单并点击'submit'时,它会将所有通过验证的检查值添加到您的模型中作为保存的:interest_id值,这样保存的值就是使复选框持续存在,即使整个表单失败验证。

如果想让形式的任何部分验证失败重置您的形式,我建议增加一个if/else语句到您在创建动作控制器。 @ object.interest_ids = []会将您对象上存储的interest_id重置为一个空数组,这将取消选中这些框。

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