【问题标题】:Nested has_many model in form repeats on Edit or if form has validation errors表单中的嵌套 has_many 模型在编辑时重复或表单存在验证错误
【发布时间】: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


【解决方案1】:

嗯,终于明白了。这是解决方案...

在控制器动作中,构建它两次:

2.times do
  @poll.poll_options.build
end

在视图中,只循环一次。显然你不能有两个循环来获得嵌套形式的两个实例:

= f.simple_fields_for :poll_options do |options|
    = options.input :label

【讨论】:

    【解决方案2】:

    试试这个:

    private
    def poll_params
      params.require(:poll).permit(poll_options_attributes: [:id, :destroy, ...other poll option params])
    end
    

    更新

    def new
      @poll = Poll.new
      @poll.poll_options.build unless @poll.poll_options.any?
    end
    

    更新 2simple_form helper 更改为simple_nested_form(不要忘记你的application.js 中的js)

    我不知道了,对不起。

    【讨论】:

    • 如果我提交一个没有一些必填字段的new 表单,仍然会遇到同样的问题,返回到显示所需错误的表单,并且仍然再次重复选项 x2
    • 刚试过@poll.poll_options.build unless @poll.poll_options.any?..还是同样的问题:(
    • @Jacob 关于表单助手的最新更新。恐怕,仅此而已。
    • 非常感谢您的帮助!这也没有解决它,但我非常感谢你的帮助!
    猜你喜欢
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多