Kellogs
Kellogs

Reputation: 471

Rails: Format JS not being picked up by data-remote

The JS is not being picked up by the data-remote of each link. I am trying to create one button that does voting and unvoting, like the old digg.com voting button. At this time because the JS is not being picked up I have two buttons each separate for voting and unvoting and I would like to combine the two. I am unsure why the JS is not being picked up. Any suggestions? Thank you.

Micropost Controller

class MicropostsController < ApplicationController 
  def vote_up
    @micropost = Micropost.find(params[:id])
    current_user.vote_exclusively_for(@micropost)
    respond_to do |format|
      format.html { redirect_to :back }
      format.js
      end
  end

   def unvote
    @micropost = Micropost.find(params[:id])
    current_user.vote_exclusively_against(@micropost)
    respond_to do |format|
      format.html { redirect_to :back }
      format.js
      end
  end
end

JS Files

*vote_up.js*

$("#<%[email protected]%>").html('<%="#{@micropost.votes_for}"%>');
$("#vote-<%[email protected]%>").html('<a href="/microposts/<%[email protected]%>/unvote" data-remote="true" class="CounterButton b2 <%[email protected]%>"></a>');

unvote.js

$("#<%[email protected]%>").html('<%="#{@micropost.votes_for}"%>');
$("#unvote-<%[email protected]%>").html('<a href="/microposts/<%[email protected]%>/vote_up" data-remote="true" class="CounterButton b2 <%[email protected]%>"><span class="CounterIcon <%[email protected]%>"></span></a>');

Micropost HTML

<div class='Counter'>
<span class='CounterNum'><span id='<%= micropost.id%>'><%=micropost.votes_for %></span></span>
<div id='vote-<%=micropost.id %>'>
<a href="/microposts/<%=micropost.id %>/vote_up" data-remote='true' class='CounterButton b2'>
<span class='CounterIcon'></span>
</a>
</div>
<div id='unvote-<%=micropost.id %>'>
<a href="/microposts/<%=micropost.id %>/unvote" data-remote='true'class='CounterButton b2'>
<span class='CounterIcon'></span>
</a>
</div>
</div>

Upvotes: 0

Views: 593

Answers (1)

James
James

Reputation: 4807

Try combining all your calls to javascript_include_tag into a single call and also include jquery_ujs:

javascript_include_tag :jquery, :jquery_ujs, :modal, :basic_js, 'http://www.google.com/jsapi

Although since you're on Rails 3.2, you should really be taking advantage of the asset pipeline which you can read more about here:

http://guides.rubyonrails.org/asset_pipeline.html

Your application.js would then look something like this:

//= require jquery
//= require jquery_ujs
//= require_tree .

And then you would simply do:

javascript_include_tag :application

But try the other method first.

Upvotes: 1

Related Questions