如何将空白复选框作为false传递给params

bra*_*rad 39 checkbox ruby-on-rails ruby-on-rails-4

我有一个表单是一个更新用户表单,其中几个元素是复选框.如果选中(这是正常工作),我想要传递给params,如果未选中(不工作),我希望传递给params.未经检查的项目甚至没有被发送到参数.如何使未经检查的项目通过为假?

形成

<%= form_tag user_url(@user), class: "form-signin", method: 'patch' do %>
 <h4>Please confirm your email.  We'll only email you if you have notifications.</h4>
  <%= email_field_tag :email, current_user.email %>
 <h4>Want to be notified when someone needs a player?  Choose which sports below.</h4>
  <%= check_box_tag :basketball, checked = true %> Basketball</br></br>
  <%= check_box_tag :indoor_volleyball, checked = true %> Indoor Volleyball</br></br>
  <%= check_box_tag :beach_volleyball, checked = true %> Beach Volleyball</br></br>
  <%= check_box_tag :soccer, checked = true %> Soccer</br></br>
  <%= check_box_tag :flag_football, checked = true %> Flag Football</br></br>
  <%= check_box_tag :hockey, checked = true %> Hockey</br></br>
  <%= check_box_tag :kickball, checked = true %> Kickball</br></br>
  <%= check_box_tag :softball, checked = true %> Softball
  <%= hidden_field_tag :user_id, :value => current_user.id %>
  <%= hidden_field_tag :user, :value => current_user %>
 <div>
  </br>
  <%= submit_tag "Submit", class:"btn btn-large btn-success" %>
 </div>
Run Code Online (Sandbox Code Playgroud)

调节器

  def update
   respond_to do |format|
   if @user.update(update_params)
     format.html { redirect_to @user, notice: 'Updates were successful.' }
     format.json { head :no_content }
    else
     format.html { render action: 'edit' }
     format.json { render json: @user.errors, status: :unprocessable_entity }
    end
   end
  end

  def update_params
    params.permit(:email, :soccer, :softball, :beach_volleyball, :indoor_volleyball, :flag_football, :basketball, :hockey, :kickball)
  end
Run Code Online (Sandbox Code Playgroud)

Jel*_*Boy 78

您需要在每个复选框前面放置一个带有空值的隐藏字段标记,例如:

<%= hidden_field_tag :basketball, '' %>
<%= check_box_tag :basketball, checked = true %> Basketball</br></br>
Run Code Online (Sandbox Code Playgroud)

然后表单知道如果没有选择任何内容,它需要使用空值填充该字段.

  • `f.check_box`为你做了这个伎俩.但是普通的ol`check_box_tag`没有.如果您没有直接绑定到ActiveRecord模型布尔属性,这是一个很好的简单解决方案,基本上就是`f.check_box`正在为您做的事情. (14认同)

vik*_*iks 5

如果有人的列类型为boolean并使用check_box_tag,则请看一下。它为我工作。 <%= hidden_field_tag :basketball, 'false' %> <%= check_box_tag :basketball, true, is_checked? %>