like/dislike button on blog w/ ajax rails

288
November 23, 2016, at 5:55 PM

Back here after I tried originally making like/dislike buttons on a blog-like site and trying to use redirect to: back and some anchors but that did not work. I am now trying to use ajax to automatically update the like or dislike button when someone clicks on the link without having the entire page reload. I know there are a lot of other questions like this but I have not been able to find one that fixes my issue. I currently have the like and dislike button working however i need to refresh the page to switch them over, meaning the counters do not update automatically. Any help is greatly appreciated:

stories controller

def upvote
  @story = Story.find(params[:id])
  @story.upvote_by(current_user)
    respond_to do |format|
    format.html {redirect_to :back}
    format.js { render layout: false }
  end
end
def downvote
  @story = Story.find(params[:id])
  @story.downvote_by(current_user)
  respond_to do |format|
    format.html { redirect_to :back }
    format.js { render layout: false }
  end
end

index.html.erb

<%= link_to like_story_path(story), method: :put, remote: true, class: "btn btn-warning btn-xs" do %>
That scared me! <span class="text-warning"> </span>  <% end %>(<%= story.get_upvotes.size %>)

<%= link_to dislike_story_path(story), method: :put, remote: true, class: "btn btn-success btn-xs" do %>
You Wimp! <span class="text-warning"></span><% end %>
(<%= story.get_downvotes.size %>)

upvote.js.erb

$('.upvote_story').bind('ajax:success', function(){
   $(this).parent().parent().find('.upvote_count').html('<%= escape_javascript @story.votes_for.size.to_s %>');
   $(this).closest('.like_story').hide();
   $(this).closest('.upvotes').html(' <%= link_to "dislike", dislike_story_path(@story), remote: true, method: :get, class: 'dislike_story' %>');
});

downvote.js.erb

$('.downvote_story').bind('ajax:success', function(){
   $(this).parent().parent().find('.upvote_count').html('<%= escape_javascript @story.votes_for.size.to_s %>');
   $(this).closest('.dislike_story').hide();
   $(this).closest('.downvotes').html(' <%= link_to "like", like_story_path(@story), remote: true, method: :get, class: 'like#story' %>');
});

_story.html.erb

<div class="story_partial" id="story_<%= story.id %>">
  <%= story.content %>
  <div id="downvote_button_<%= story.id %>">
    <%= link_to "dislike", downvote_path, method: "post", remote: true %>
  </div>
</div>
<div class="story_partial" id="story_<%= story.id %>">
  <%= story.content %>
  <div id="upvote_button_<%= story.id %>">
    <%= link_to "like", upvote_path, method: "post", remote: true %>
  </div>
</div>

and routes:

 resources :stories do
   member do
    put :like, to:'stories#upvote'
    put :dislike, to:'stories#downvote'
  end
end 

UPDATE: This is what I receive from my console when I click a "Like" link under a blog post:

  Started PUT "/stories/7/like" for 96.252.66.43 at 2015-11-02 13:32:38 +0000
Cannot render console from 96.252.66.43! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by StoriesController#upvote as JS
  Parameters: {"id"=>"7"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 2]]
  Story Load (0.2ms)  SELECT  "stories".* FROM "stories" WHERE "stories"."id" = ? LIMIT 1  [["id", 7]]
   (0.2ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."voter_id" = ? AND "votes"."voter_type" = ? AND "votes"."vote_scope" IS NULL  [["votable_id", 7], ["votable_type", "Story"], ["voter_id", 2], ["voter_type", "User"]]
  ActsAsVotable::Vote Load (0.2ms)  SELECT  "votes".* FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."voter_id" = ? AND "votes"."voter_type" = ? AND "votes"."vote_scope" IS NULL  ORDER BY "votes"."id" DESC LIMIT 1  [["votable_id", 7], ["votable_type", "Story"], ["voter_id", 2], ["voter_type", "User"]]
   (0.1ms)  begin transaction
  SQL (0.6ms)  UPDATE "votes" SET "vote_flag" = ?, "updated_at" = ? WHERE "votes"."id" = ?  [["vote_flag", "t"], ["updated_at", "2015-11-02 13:32:38.350587"], ["id", 1]]
   (8.9ms)  commit transaction
   (0.2ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ?  [["votable_id", 7], ["votable_type", "Story"]]
  Rendered stories/upvote.js.erb (2.4ms)
Completed 200 OK in 186ms (Views: 3.8ms | ActiveRecord: 10.8ms)

Then when i hit refresh i get this.. I did not copy all the GET requests since there are about 19 of them

Started GET "/" for 96.252.66.43 at 2015-11-02 13:33:54 +0000
Cannot render console from 96.252.66.43! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by StoriesController#index as HTML
  Story Load (0.3ms)  SELECT "stories".* FROM "stories"
   (0.2ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = 't' AND "votes"."vote_scope" IS NULL  [["votable_id", 6], ["votable_type", "Story"]]
   (0.1ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = 'f' AND "votes"."vote_scope" IS NULL  [["votable_id", 6], ["votable_type", "Story"]]
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]
   (0.2ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = 't' AND "votes"."vote_scope" IS NULL  [["votable_id", 7], ["votable_type", "Story"]]
   (0.1ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = 'f' AND "votes"."vote_scope" IS NULL  [["votable_id", 7], ["votable_type", "Story"]]
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]
   (0.2ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = 't' AND "votes"."vote_scope" IS NULL  [["votable_id", 8], ["votable_type", "Story"]]
   (0.1ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = 'f' AND "votes"."vote_scope" IS NULL  [["votable_id", 8], ["votable_type", "Story"]]
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]
   (0.2ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = 't' AND "votes"."vote_scope" IS NULL  [["votable_id", 9], ["votable_type", "Story"]]
   (0.2ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = 'f' AND "votes"."vote_scope" IS NULL  [["votable_id", 9], ["votable_type", "Story"]]
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]
   (0.1ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = 't' AND "votes"."vote_scope" IS NULL  [["votable_id", 10], ["votable_type", "Story"]]
   (0.1ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = 'f' AND "votes"."vote_scope" IS NULL  [["votable_id", 10], ["votable_type", "Story"]]
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]
   (0.2ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = 't' AND "votes"."vote_scope" IS NULL  [["votable_id", 11], ["votable_type", "Story"]]
   (0.2ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = 'f' AND "votes"."vote_scope" IS NULL  [["votable_id", 11], ["votable_type", "Story"]]
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]
  Category Load (0.2ms)  SELECT "categories".* FROM "categories"
  Rendered stories/index.html.erb within layouts/application (64.6ms)
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 2]]
  Rendered layouts/_header.html.erb (1.8ms)
Completed 200 OK in 215ms (Views: 211.7ms | ActiveRecord: 2.8ms)

Started GET "/assets/style.self-9116d042c0a58f16b620f2fcef2e66bc9e7bb9e1d9875291cf4c94d80f232344.css?body=1" for 96.252.66.43 at 2015-11-02 13:33:55 +0000
Cannot render console from 96.252.66.43! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255

Started GET "/assets/application.self-b9d18442eb6f7484fafe00524db309cada26b681530b4c56554a4331e3326a18.css?body=1" for 96.252.66.43 at 2015-11-02 13:33:55 +0000
Cannot render console from 96.252.66.43! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255

Started GET "/assets/bootstrap/affix.self-f7aef9d98ee5ece34a6a92a6a15bba777d93e8d908b75c95a85088277f394200.js?body=1" for 96.252.66.43 at 2015-11-02 13:33:55 +0000
Cannot render console from 96.252.66.43! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255

Started GET "/assets/bootstrap/collapse.self-93820e9b486e375a7fb4477602def3a6f8381fa6d50938d5378297ffbe4a1248.js?body=1" for 96.252.66.43 at 2015-11-02 13:33:55 +0000
Cannot render console from 96.252.66.43! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255

Started GET "/assets/bootstrap/button.self-d19f3e2bcd3a7a4d75c11b9141b3fabd2c11987da1e99c85548ec3ecf8db30c3.js?body=1" for 96.252.66.43 at 2015-11-02 13:33:55 +0000
Cannot render console from 96.252.66.43! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255

Started GET "/assets/bootstrap/alert.self-896ab026e6823f5cef2441e07dac53d0692a5b772ac58b1ce20aa624c342d3f4.js?body=1" for 96.252.66.43 at 2015-11-02 13:33:55 +0000
Cannot render console from 96.252.66.43! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255

Started GET "/assets/bootstrap/dropdown.self-30536ae4d54b2685c26b5787ed0eb549a9075717fe690cce6270873bedf2df00.js?body=1" for 96.252.66.43 at 2015-11-02 13:33:55 +0000
Cannot render console from 96.252.66.43! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255

When I inspect one of the dislike buttons i have this:

<a class="btn btn-success btn-xs" data-remote="true" rel="nofollow" data-method="put" href="/stories/20/dislike">
You Wimp! <span class="text-warning"></span></a>

Thanks so much in advance!

Answer 1

You can try the following code with right syntax and flow. These following changes will solve your problem. But you can re-organise your code with more cleaner one. In your controller:

def upvote
  @story = Story.find(params[:id])
    respond_to do |format|
     if @story.upvote_by(current_user)
      format.html {redirect_to :back}
      format.js { render layout: false }
     else
      # add your proper message to user why its not possible
      format.html {redirect_to :back}
      format.js { render "alert('failed to give upvote')" }
     end
   end
end

In your upvote js file. Remove the ajax success block.

  # ensure you got the right selector.
  #instead of escape_javascript use j
  $('.downvote_story').parent().parent().find('.upvote_count').html('<%= j  @story.votes_for.size.to_s %>');
  $('.downvote_story').closest('.like_story').hide();
  $('.downvote_story').closest('.upvotes').html(' <%= link_to "dislike", dislike_story_path(@story), remote: true, method: :get, class: 'dislike_story' %>');
Rent Charter Buses Company
READ ALSO
Load function in jQuery does not work

Load function in jQuery does not work

I am trying to load a header and footer file into jQuery, so I wrote the following code:.

365
jQuery/CSS3 UI list with action items library

jQuery/CSS3 UI list with action items library

I am looking of a list component that allows me to select action item on tap. I was not able to find any jQuery UI/Bootstrap library.

336
How to avoid the session timeout in non-login situation php?

How to avoid the session timeout in non-login situation php?

I have set 2 min for session timeout and if it occurred the page[nnn]will redirect to a session timeout page. .

315
execute a php file on selection of dropdown value

execute a php file on selection of dropdown value

i have been searching a solution for days and i have tried ajax/jquery methods posted online but it just wouldnt work. I have a drop down list which gets its value from the database.

343