【问题标题】:Rails circular and dynamic nested formRails 循环和动态嵌套形式
【发布时间】:2018-04-09 10:01:39
【问题描述】:

我正在尝试使用循环和动态嵌套表单创建一个“博客”示例,但我无法让它工作,它只会永远加载,我需要终止服务器为了阻止它。

博客有 cmets,评论有 cmets。就是这样。

请帮帮我:)

我正在使用:

  • 导轨 (5.1.6)
  • 活动记录 (5.1.6)
  • simple_form (3.5.1)
  • 茧(1.2.11)
  • jquery-rails (4.3.1)
  • haml (5.0.4)

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。

【问题讨论】:

  • 我不太确定您是否应该在这里使用嵌套属性。而是将它们视为两个独立的资源,每个资源都有一个标准的 CRUD 控制器。我真的不明白为什么您需要在同一个请求中创建博客文章和 cmets,或者在同一个请求中创建评论和回复。
  • 是的,你是对的,这只是一个例子,对不起。真正的项目有类别,里面有类别。

标签: ruby-on-rails haml simple-form nested-forms cocoon-gem


【解决方案1】:

嗯...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

【讨论】:

  • 没错,cocoon 或 rails 中任何基于服务器的嵌套字段处理程序都会有这个问题。在渲染link_to_add_association 时,我们预渲染要插入的嵌套项目的表单,再次包含相同的link_to_add_association,这将渲染......你得到了漂移。如果您确实需要动态无限深度嵌套类别(可能就是这种情况),那么您将不得不采用 ajax/xhr 路线。限制嵌套的可能更清洁的解决方案:github.com/nathanvda/cocoon-self_join-form/blob/master/app/…
  • 是的,我就是这样做的,但是如果你有 10 名员工,你将渲染 50 个表单并且需要很长时间来加载。
  • Cocoon 允许预渲染服务器上的所有内容,因此您不必使用 ajax/xhr。但是在服务器上进行预渲染需要时间,尤其是当表单是自我引用的时候,就像你的情况一样。使用 ajax/xhr 的更特别的解决方案有很多优点。它还取决于 UI:您是否需要一个包含所有嵌套数据的表单(1 次提交)。
猜你喜欢
  • 2012-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-24
  • 2021-01-15
  • 2016-04-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多