Updating Elements in Rails with Ajax

The app allows users to vote for embedded videos. When users click the up and down arrows, the whole page is updated to refresh points. I’ve been trying to vote for AJAX for several months now. I would like to get the simplest solution you can offer, even if it is not the most effective. Any ideas?

My upand downactions fromapp/controllers/links_controller

  ....

  def up
    @link = Link.find(params[:id])
    @link.update_attribute :points, @link.points + 1
    redirect_to :back 
  end

  def down 
    @link = Link.find(params[:id])
    @link.update_attribute :points, @link.points - 1
    redirect_to :back 
  end 

  ....

links_listPartial minimal version , app/views/links/_links_listwhich I render in other views using various sorting methods

  <% @links.each do |link| %>
        <div class="row">
            <div class="span2">
                <%= link_to (image_tag ("up.png")), up_link_url(link), :method => :put %> 
                <%= link.points %>
                <%= link_to (image_tag ("down.png")), down_link_url(link), :method => :put %>
            </div>
            <div class="span8">
                <%= link_to strip_tags(link.title), link %> 
            </div>
        </div>
  <% end %>
  • I would like to achieve this without using an external gem, the application is already in production
  • , , 3 , ajax . , , .
  • Rails 3.1

!

+5
1

Ajax Rails 3.1. , jQuery JavaScript; , jquery-rails gem, .

:

....

def up
  @link = Link.find(params[:id])
  @link.update_attribute :points, @link.points + 1
  respond_to do |format|
    format.html {redirect_to :back}
    format.js
  end
end

def down 
  @link = Link.find(params[:id])
  @link.update_attribute :points, @link.points - 1
  respond_to do |format|
    format.html {redirect_to :back}
    format.js
  end
end 

....

:

<% @links.each do |link| %>
  <div class="row">
    <div class="span2">
      <%= link_to (image_tag ("up.png")), up_link_url(link), :method => :put, :remote => true %> 
      <%= link.points %>
      <%= link_to (image_tag ("down.png")), down_link_url(link), :method => :put, :remote => true %>
     </div>
     <div class="span8">
       <%= link_to strip_tags(link.title), link %> 
     </div>
  </div>
 

, up.js.erb down.js.erb, app/views/links/, JavaScript :

$(".span2").html("This post has <%= @link.points %> points.")

Prototype -, ; JavaScript, up.js.erb down.js.erb, Prototype-y jQuery-y.

+10

All Articles