【发布时间】: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