How do you make a form out of a polymorophic table?

孤者浪人 提交于 2019-12-24 10:57:29

问题


I am trying to create a comment that could comment on other comments but are all derived from a single post.

What is especially troubling for me is trying to figure out how to make it so that this can all be achieved in the post show and not its edit or new. Is this archtecturally reasonable?

That way I can access it via Post.comments, or Comment.comments etc. or Comments.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 my comment table have a :text and :post_id attribute. Though I don't think it needs a :post_id,

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

Here's my awful attempt :

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

But it seems unecessary to do that.


回答1:


Two Key components to finishing this was this :

Because its in the show, I need to specify the URL to which this posts :

- 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'

But I was confused because where there were no errors, there was no textfield!

That because my controller didn't mention one. So I added this to def show

@comment = Comment.new

Ta da, it works now.

Full Code

Controller:

  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


来源:https://stackoverflow.com/questions/3938173/how-do-you-make-a-form-out-of-a-polymorophic-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!