Rails 循环动态嵌套形式

Rails circular and dynamic nested form

我正在尝试使用 循环和动态嵌套形式 创建一个 'blog' 示例,但我无法让它工作,它一直在加载我需要杀死服务器才能停止它。

一个博客有评论,一个评论有评论。就这些了。

请帮助我:)

我正在使用:

blog.rb

class Blog < ApplicationRecord
  validates :message, presence: true

  has_many :comments, inverse_of: :blog

  accepts_nested_attributes_for :comments,
    allow_destroy: true,
    reject_if: ->(attributes) {attributes[:text].blank?}
end

comment.rb

class Comment < ApplicationRecord
  belongs_to :blog, inverse_of: :comments, optional: true
  belongs_to :comment, optional: true
  has_many :comments, inverse_of: :comment

  accepts_nested_attributes_for :comments,
    allow_destroy: true,
    reject_if: ->(attributes) {attributes[:text].blank?}
end

form.html.haml

= simple_form_for blog do |f|
  = f.input :message

  .comments
    = f.simple_fields_for :comments do |comment|
      = render 'comment_fields', f: comment

  = link_to_add_association 'Add', f, :comments, data: {association_insertion_node: '.comments', association_insertion_method: :append}

  = f.button :submit

_comment_fields.html.haml

.nested-fields.ml-3
  = link_to_remove_association 'Remove', f

  = f.input :text

  = f.simple_fields_for :comments do |sub_comment|
    = render 'comment_fields', f: sub_comment

= link_to_add_association 'Add', f, :comments, data: {association_insertion_node: '.comments', association_insertion_method: :append}

我也试过 Railscasts example,但它没有用,因为 link_to_add_fields 帮助程序加载了 comment_fields 文件并且它里面有 link_to_add_fields。

嗯……it's an issue with the cocoon gem。我找到了一个可能的(和肮脏的)解决方案,如果我限制嵌套,它就可以工作。

.nested-fields.ml-3
  = f.input :text

  - index ||= 0
  - index += 1
  - if index < 10
    = link_to_add_association 'Add', f, :comments, data: {association_insertion_method: :append}, render_options: {locals: {index: index}}

  = link_to_remove_association 'Remove', f

  = f.simple_fields_for :comments do |sub_comment|
    = render 'comment_fields', f: sub_comment