gpt4 book ai didi

ruby-on-rails - Rails has_many 更新为空数组

转载 作者:行者123 更新时间:2023-12-02 04:46:01 25 4
gpt4 key购买 nike

有如下表单代码:

= form_for @task, html: { class: 'form-horizontal' } do |f|
.form-group
.col-sm-9.col-sm-offset-3
= render partial: 'shared/form_errors', locals: { subject: @task }
.form-group
label.col-sm-3.control-label for='title' Title
.col-sm-9
= f.text_field :title, class: 'form-control', placeholder: 'Title'
.form-group
label.col-sm-3.control-label for='description' Description
.col-sm-9
= f.text_area :description, class: 'form-control', placeholder: 'Description'
.form-group
label.col-sm-3.control-label Teams
.col-sm-9
ul
- Team.all.each do |t|
li
= check_box_tag "team_ids", t.id, @task.teams.include?(t), name: 'task[team_ids][]'
= t.name
.form-group
.col-sm-9.col-sm-offset-3
= f.submit 'Save', class: 'btn btn-success'

如您所见,我可以通过复选框为我的任务选择团队。我的 Controller :

  def update
@task = Task.find(params[:id])
if @task.update(task_params)
redirect_to tasks_path, flash: { alert: TASK_UPDATING_MESSAGE }
else
render 'edit'
end
end

private
def task_params
params.require(:task).permit(:title, :description, team_ids: [])
end

如果我更新一些选中的团队的任务,效果会很好;但我也希望能够检查任何团队并使用空的团队更新任务。但是在这种情况下 tasks_params 没有 team_ids 数组,并且更新不起作用。我该如何解决?谢谢!

最佳答案

我的理解是,当您提交表单时没有任何检查,您有 params[:task][:team_ids] = nil

你可以试试这样的:

def task_params
params[:task][:team_ids] = [] if params[:task][:team_ids].nil?
params.require(:task).permit(:title, :description, team_ids: [])
end

关于ruby-on-rails - Rails has_many 更新为空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32770508/

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