samnang
9/18/2011 - 6:37 PM

Unobtrusive AJAX with Rails 3.1

Unobtrusive AJAX with Rails 3.1

<div class="comment">
  <strong><%= comment.name %></strong>
  <em>on <%= comment.created_at.strftime('%b %d, %Y at %I:%M %p') %></em>
  <%= simple_format comment.content %>
</div>
class CommentsController < ApplicationController
  respond_to :html, :js

  def index
    @comments = Comment.all
  end

  def create
    @comment = Comment.new(params[:comment])

    @comment.save

    respond_with @comment, :location => comments_url
  end
end
$('<%= escape_javascript(render(:partial => @comment))%>')
  .appendTo('#comments')
  .hide()
  .fadeIn()

$('#new_comment')[0].reset()

$('#comments_count').html '<%= comments_count %>'
<% title "Comments for Ajax in Rails 3.1" %>

<div id="comments_count"><%= comments_count %></div>

<div id="comments">
  <%= render @comments %>
</div>

<h3>Add your comment:</h3>

<%= form_for Comment.new, :remote => true do |f| %>
  <%= f.error_messages %>
  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.label :content, "Comment" %><br />
    <%= f.text_area :content, :rows => '12', :cols => 35 %>
  </p>
  <p><%= f.submit %></p>
<% end %>