Search code examples
ruby-on-railsajaxgsubvoting

acts_as_votable ajax not updating the data until I refresh the whole page


Hi I'm newbie in rails

actually voting is works fine but it's not updating the data until I refresh the whole page

Here is my error when I voting

Here is my code

routes.rb

resources :posts do
 match :vote, via: [:post, :delete], on: :member
end

controller.rb

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy, :vote]
  respond_to :js, :html, :json
  def vote
   @post = Post.find(params[:id])
   if request.post?
       @post.upvote_from current_user
   elsif request.delete?
       @post.downvote_from current_user
   end
   respond_to do |format|
      format.html { redirect_to :back }
      format.js
   end
  end

vote.js.erb

$("<%=j @post.id %>").html("<%=j render partial: "posts/vote", locals: { post: @post } %>");

_vote.html.erb

<% voted   = current_user.voted_for? post %>
<% styling = voted ? "" : "un" %>
<% arrow   = voted ? "up" : "down" %>
 <% method  = voted ? :delete : :post %>

 <%= link_to vote_post_path(post), method: method, remote: true, class: '# 
{styling}like_post', id: post.id do %>
    <button type="button" class="btn btn-info" aria-label="Left Align">
           <i class="fa fa-arrow-<%= arrow %>"></i>
        <span class="badge vote_count"><%= post.get_upvotes.size %></span>
     </button>
 <% end %>

show.html.erb

<%= render partial: "vote", locals: { post: @post } %>

application.js

//= require rails-ujs
//= require turbolinks
//= require_tree .
//= require jquery3
//= require popper
//= require bootstrap-sprockets

Solution

  • $("<%= @post.id %>").html("<%=j render partial: "posts/vote", locals: { post: @post } %>");
    

    no need for j escaping if its not a script/text. Assuming post has id 5 and so getting error

    undefined method `gsub' for 5:Integer