我有一个表单是一个更新用户表单,其中几个元素是复选框.如果选中(这是正常工作),我想要传递给params,如果未选中(不工作),我希望传递给params.未经检查的项目甚至没有被发送到参数.如何使未经检查的项目通过为假?
形成
<%= form_tag user_url(@user), class: "form-signin", method: 'patch' do %>Please confirm your email. We'll only email you if you have notifications.
<%= email_field_tag :email, current_user.email %>Want to be notified when someone needs a player? Choose which sports below.
<%= check_box_tag :basketball, checked = true %> Basketball <%= check_box_tag :indoor_volleyball, checked = true %> Indoor Volleyball <%= check_box_tag :beach_volleyball, checked = true %> Beach Volleyball <%= check_box_tag :soccer, checked = true %> Soccer <%= check_box_tag :flag_football, checked = true %> Flag Football <%= check_box_tag :hockey, checked = true %> Hockey <%= check_box_tag :kickball, checked = true %> Kickball <%= check_box_tag :softball, checked = true %> Softball <%= hidden_field_tag :user_id, :value => current_user.id %> <%= hidden_field_tag :user, :value => current_user %><%= submit_tag "Submit", class:"btn btn-large btn-success" %>
调节器
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
JellyFishBoy.. 78
您需要在每个复选框前面放置一个带有空值的隐藏字段标记,例如:
<%= hidden_field_tag :basketball, '' %> <%= check_box_tag :basketball, checked = true %> Basketball
然后表单知道如果没有选择任何内容,它需要使用空值填充该字段.
如果有人的列类型为boolean并使用check_box_tag,则请看一下。它为我工作。
<%= hidden_field_tag :basketball, 'false' %>
<%= check_box_tag :basketball, true, is_checked? %>
您需要在每个复选框前面放置一个带有空值的隐藏字段标记,例如:
<%= hidden_field_tag :basketball, '' %> <%= check_box_tag :basketball, checked = true %> Basketball</br></br>
然后表单知道如果没有选择任何内容,它需要使用空值填充该字段.