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

 mobiledu2502917073 发布于 2023-02-12 19:59

我有一个表单是一个更新用户表单,其中几个元素是复选框.如果选中(这是正常工作),我想要传递给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

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

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

    2023-02-12 20:01 回答
  • 您需要在每个复选框前面放置一个带有空值的隐藏字段标记,例如:

    <%= hidden_field_tag :basketball, '' %>
    <%= check_box_tag :basketball, checked = true %> Basketball</br></br>
    

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

    2023-02-12 20:02 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有