我正试图创建一个博客'使用循环和动态嵌套表单的示例,但我无法使其正常工作,它只是永远加载,我需要终止服务器才能阻止它。
博客有评论,评论有评论。这就是全部。
请帮帮我:)。
我正在使用:
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。
答案 0 :(得分:0)
嗯...... 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