Ruby on rails 在Rails 5中以表格_重新加载页面时保留复选框值

Ruby on rails 在Rails 5中以表格_重新加载页面时保留复选框值,ruby-on-rails,ruby-on-rails-5,erb,Ruby On Rails,Ruby On Rails 5,Erb,我有一个使用form\u和创建的表单。我需要的是在重新加载页面后保留使用该表单提交的值。我可以保存text\u字段的值,但不能保存复选框的值。为了达到同样的效果,我应该在代码中更改什么 html.erb <%= form_with url: search_path, id: :search_by_filter, method: :get, local: true do |f| %> &

我有一个使用
form\u和
创建的表单。我需要的是在重新加载页面后保留使用该表单提交的值。我可以保存
text\u字段的值
,但不能保存
复选框的值
。为了达到同样的效果,我应该在代码中更改什么

html.erb

<%= form_with url: search_path,
                      id: :search_by_filter,
                      method: :get, local: true do |f| %>   

  <div>
    <p><strong>Search by Name</strong></p>
    <%= f.label 'Name' %>
    <%= f.text_field :name, value: params[:name] %>
  </div>
  <br>

  <div>
    <%= label_tag  do %>
      <%= f.check_box :only_students, checked: params[:only_students] %>
      Show only students
    <% end %>
  </div>
  <br/>


  <div class="submit_button">
    <%= f.submit :Search %>
  </div>

<% end %>
def get_desired_people(params)
  people = Person.includes(:country, :state, :university).order(id: :desc)  
  people = people.where(is_student: params[:only_students]) if params[:only_students]
  people = people.where(name: params[:name]) if params[:name].present?
  people
end
在这里,我可以保留
params[:name]
的值,但不能保留
params[:only_students]
的值。提交表单后,它始终保持未选中状态。如何保留选中和未选中的值?

f.check\u box
check\u box\u标记
应通过布尔值进行检查,并且每个参数都是一个字符串(如果存在字符串,则该字符串始终计算为true),因此您应该执行以下操作:
选中:参数[:仅学生]。是否存在?
您不必担心param的值,因为未选中的param在发布时不会被发送

编辑:

以上内容适用于
复选框标记
f.复选框
很棘手,您应该仔细阅读说明:
您描述的行为似乎非常正确,您可以处理它,或者在不更新模型属性时切换到
复选框标签
,作为更好的选择

以上所有解决方案都不适用于我。试试这个:

<%= check_box_tag :only_students, true, params[:only_students] %>


您是否只尝试了“是”。是的。即使我检查并提交表单,它仍然保持未选中状态。提交后,您的参数[:仅学生]是否仍保留在您的URL中?是的。它就在那里。如果未选中,则在提交后的url中,
params[:only_students]=0
。如果选中,则它是
params[:only_students]=0¶ms[:only_students]=1
如果我这样做,它会工作:
。是否有更好的方法?无论复选框是否选中,该值始终存在。就像我在上面的评论中提到的:如果未选中,那么在提交后的url中,params[:only_students]=0。如果选中,则为params[:only_students]=0¶ms[:only_students]=1ok。我的错误。
f.check_box
check_box_tag
之间有区别,在这里的“Gotcha”下,你可以找到发生了什么的解释,我想你可以简单地跳过添加
checked:params[:only_students]
,因为如果没有它,它可能会设置正确是的。我试过了。它不保留选中的值。表单提交后,它始终处于未选中状态。只有当我这样做时它才起作用:
好的,我明白了。这不是一个更新表单,这就是原因。而你的解决方案是唯一的。但是,我可以推荐两件事中的一件:1)在controller
@only_students=params[:only_students]='1'
中创建一个bool,并在需要的地方使用它2)在不更新模型属性时切换到
复选框标签