【发布时间】:2017-08-23 14:44:44
【问题描述】:
如果您有以下两个模型并使用 simple_form gem 创建表单:
class Poll < ApplicationRecord
has_many :poll_options, dependent: :destroy
accepts_nested_attributes_for :poll_options
end
class PollOption < ApplicationRecord
belongs_to :poll
end
控制器:
class PollsController < ApplicationController
def new
@poll = Poll.new
@poll.poll_options.build
end
def edit
end
private
def poll_params
# params.fetch(:poll, {}).permit(:poll_options_attributes)
# params.require(:poll).permit!
params.require(:poll).permit(:title, poll_options_attributes: [ :id, :destroy, :poll_id, :label ])
end
end
形式:
= simple_form_for(@poll) do |f|
= f.input :title, required: true
= f.simple_fields_for :poll_options do |option_a|
= option_a.input :label
= f.simple_fields_for :poll_options do |option_b|
= option_b.input :label
如果我在没有必填字段(标签)的情况下故意提交,页面会重新加载 4 个选项,然后我再次提交 6 个选项等。出于某种原因,它不断向表单添加两个选项。
此外,编辑投票会加载 4 个选项,而不是数据库中保存的 2 个(它显示了选项的所有可能组合)。
知道为什么会发生这种情况吗?
把我的头撞在墙上 2 天。任何帮助将不胜感激。
【问题讨论】:
-
请显示您的控制器允许的参数。您是否将
:id添加到poll_options_attributes? -
@cnnr 已更新参数。我试过
params.fetch(:poll, {}).permit(:poll_options_attributes)和params.require(:poll).permit! -
你的更新方法怎么样?
标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-5 simple-form