Ajax render a template


#1

In my blog a user can add comments. I want an Ajax call to add the
comment to the bottom of the comments list.

How to i return a comment thats is in the comment template and add it to
the bottom of the page. I have gotten as far as rendering some text
back to the form and the comment doesn’t display until i refresh.

This is my _newcomment.rhtml form to create a new comment

Leave a Reply <%= form_remote_tag(:update => 'newcomments', :url => {:action => :comment, :id => @post}, :position => "before") %> <%= render :partial => 'commentform' %>

<%= submit_tag "Comment!" %>

<%= end_form_tag %>

This is my def in the blog controller t handle the creation of the new
comment
def comment
Post.find(params[:id]).comments.create(params[:comment])
render_text “return the comment”
end

This is my partial to display a comment _comment.rhtml

<%= comment.name %> Says:

<%= comment.comment %>

<%= comment.created_at.to_s(:long) %>



#2

using rjs, i’d do it something like so…

in your post view

...your post here
<%= render :partial => "comment", :collection => @comments %>
<%= render :partial => "comment_form" %>

_comment_form.rhtml

<%= form_remote_tag(:url => {:action => :comment, :id => @post }) %>

<%= submit_tag "Comment!" %>

<%= end_form_tag %>

_comment.rhtml

<%= comment.name -%> Says:

<%= comment.comment -%>

<%= comment.created_at.to_s(:long) -%>


controller:

def comment

create comment

@comment = Post.find(@params[:id]).comments.create(@params[:comment])
render :update do |page|
# show the new comment at the top of the comments display
page.insert_html(:top, “comments”, :partial => “comment”)
# quick and dirty way to empty the form that was just submitted
page.replace_html(“comment_form”, :partial => “comment_form”)
end
end


#3

Chris H. wrote:

using rjs, i’d do it something like so…

Using RJS?? Does this mean you have template file ending in RJS which
adds a comment to the end of the list?


#4

rjs templates.

http://weblog.rubyonrails.org/articles/2006/03/28/rails-1-1-rjs-active-record-respond_to-integration-tests-and-500-other-things

read the first section and you’ll get an taste of what rjs templates are
capable of.