-1

I am using the gem "acts_as_votable" in my Rails application so that Users can vote on Posts. It all works fine.

enter image description here

But if you upvote or downvote a post, the entire page refreshes. I want to change this by implementing Ajax, which should be the ideal solution to not refresh the entire page. This is what I have so far:

routes.rb

resources :posts do 
member do
  put "like", to: "posts#upvote"
  put "dislike", to: "posts#downvote"
end
end

post.rb

class Post < ActiveRecord::Base

belongs_to :user
acts_as_votable

validates :user_id, presence: true
validates :content, presence: true, length: { maximum: 320,
too_long: "%{count} characters is the maximum allowed" }
default_scope -> { order(created_at: :desc) }

end

posts_controller.rb

class PostsController < ApplicationController

def index
..stuff here..
end

def new 
..stuff here..
end

def create
..stuff here..
end

def destroy
..stuff here..
end

def upvote
  @post = Post.find(params[:id])
  @post.upvote_by current_user
  redirect_to :back
end  

def downvote
  @post = Post.find(params[:id])
  @post.downvote_by current_user
  redirect_to :back
end

private
def post_params # allows certain data to be passed via form.
    params.require(:post).permit(:user_id, :content)
end

end

explore.html.erb

<% if @posts.each do |p| %>
<div class="panel-body">
  <p class="post-content"><%= auto_link(p.content, :html => { :target => '_blank' }) %></p>

  <%=link_to like_post_path(p), method: :put, class: 'btn btn-default btn-sm' do %>
    <span class="glyphicon glyphicon-chevron-up"></span> like <%=p.get_upvotes.size%></td>
  <% end %>

 <%=link_to dislike_post_path(p), method: :put, class: 'btn btn-default btn-sm' do %>
   <span class="glyphicon glyphicon-chevron-down"></span> dislike <%=p.get_downvotes.size%></td>
 <%end%>

</div>
<% end %>

How do I convert what I have to Ajax?

naridi
  • 77
  • 2
  • 8
  • 2
    I'm voting to close this question as off-topic because it shows no effort to actually solve the problem and is rather just code fishing. – max Jan 09 '17 at 01:51

1 Answers1

1

The way I do is to send an ajax get request to my controller and handle it all there like you: (post_controller.rb)

  def toggle_approve
    @a = Post.find(params[:id])
    @a.toggle!(:visible)
    render :nothing => true      # I don't my controller to redirect or render
  end

In my view I create an Ajax link like this (_post.erb):

<%= link_to "Approve", toggle_approve_post_path(post), :remote => true %>

In my route I have a custom route in my post routes (routes.rb):

resources :posts do
    get 'toggle_approve',   :on => :member
  end
Alexander Luna
  • 5,261
  • 4
  • 30
  • 36