【问题标题】:How do you make a form out of a polymorophic table?如何用多态表制作表格?
【发布时间】:2010-10-14 22:40:31
【问题描述】:

我正在尝试创建一个可以评论其他 cmets 但均来自单个帖子的评论。

对我来说特别麻烦的是试图弄清楚如何制作它,以便这一切都可以在后期展示中实现,而不是它的编辑或新的。这在架构上合理吗?

这样我可以通过Post.commentsComment.comments等或Comments.parent访问它

我的模特:

#comment.rb

  belongs_to  :post
  belongs_to  :parent, :class_name => 'Comment'
  has_many    :children, :class_name => 'Comment'

  validates_presence_of :text

#post.rb

  has_many                      :comments
  accepts_nested_attributes_for :comments

posts_controller

def show
  @post = Post.find(params[:id])


  respond_to do |format|
    format.html # show.html.erb
    format.xml  { render :xml => @post }
  end
end

routes.rb

resource :comments

我让我的评论表有一个:text:post_id 属性。虽然我认为它不需要:post_id

我的表单应该是什么样子,应该在哪里?

这是我糟糕的尝试:

  - form_for @post do |f|
    - f.fields_for :comments do |c|
      = f.label 'Comments'
      = f.text_area :text
      = f.submit 'Submit'

但似乎没有必要这样做。

【问题讨论】:

    标签: ruby-on-rails forms nested nested-forms


    【解决方案1】:

    完成这项工作的两个关键部分是:

    因为它在节目中,我需要指定此帖子的 URL:

    - form_for @post do |f|
      - f.fields_for :comments, @comment, :url => edit_post_path(@post) do |c|
        = c.label 'Comments'
        = c.text_area :text
        = c.submit 'Submit'
    

    但我很困惑,因为没有错误,就没有文本字段!

    那是因为我的控制器没有提到一个。所以我把这个加到def show

    @comment = Comment.new
    

    Ta da,现在可以了。

    完整代码

    控制器:

      def show
        @post = Post.find(params[:id])
        @comment = Comment.new
    
        respond_to do |format|
          format.html # show.html.erb
          format.xml  { render :xml => @post }
        end
      end
    

    【讨论】:

      猜你喜欢
      • 2010-10-28
      • 1970-01-01
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      相关资源
      最近更新 更多