gpt4 book ai didi

ruby-on-rails - 如何将空白复选框作为 false 传递给参数

转载 作者:行者123 更新时间:2023-12-03 07:23:40 29 4
gpt4 key购买 nike

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

表格

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

Controller

  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

最佳答案

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

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

然后,表单知道如果未选择任何内容,则需要用空值填充该字段。

关于ruby-on-rails - 如何将空白复选框作为 false 传递给参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20379311/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com