How do you make a form from a polymorphic table?

I am trying to create a comment that could comment on other comments, but they all come from the same post.

What bothers me especially, I’m trying to figure out how to make it so that all this can be achieved in a post show, not in editing it or in a new one. Is this architecturally reasonable?

That way I can access it through Post.commentsor Comment.commentsetc. orComments.parent

My models:

#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

I made a comment table with the :textand attribute :post_id. Although I don’t think he needs it :post_id,

What should my form look like, where should it be?

Here is my terrible attempt:

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

But it does not need to be done.

+1
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
+1

Source: https://habr.com/ru/post/1769463/


All Articles