Search code examples
ruby-on-railsrubyruby-on-rails-3formsujs

Rails 3.1 Post/Comment model for blog -- How to submit comments via ajax?


I'm trying to learn about using remote forms and using the example of an app where the Post model has_many Comments.

Assuming i have used the generic rails scaffolding to create/setup the post/comment model, controllers, default views, routes, etc, -- what should my app/views/posts/show.html look like?

Specific i am confused about:

  1. Where should the comment form post to?
  2. What parameters should be included?
  3. Do i NEED to use a hidden attribute such as f.hidden_field :post_id, :value => @post.id

Thank you!


Solution

  • Assuming that your post has_many comments...

    routes.rb (Nested Resources)

    resources :posts do
      resources :comments
    end
    

    In your comments_controller

    def create
      @post = Post.find(params[:post_id]
      @comment = @post.comment.build(params[:comment])
      if @comment.save
      ...
    end
    

    In the form:

    =form_for [@post, @comment], :remote => true do |f|
      =f.text_field :text
      =f.submit