I have a Thing
model that has many upvotes via an UpVote
model. I want to be able to create a new UpVote
object via Ajax from things/show
and increment the upvote total without refreshing the page.
Creating a new UpVote
record via Ajax works, however I cannot increment the upvote count in the view.
How can I increment the upvote totals upon successful creation of an upvote?
Here is what I have tried so far:
views/things/show.html.erb
<div id= "thing">
<div id="upvote">
<%= @thing.up_votes.count %>
</div>
<div id= "vote">
<%= link_to "upvotething", upvote_thing_path(@thing.id), :remote => true, :id => "new_upvote_link", method: :post, :class => "btn btn-small" %>
</div>
</div>
views/things/create.js.erb
$('#new_up_vote').remove();
$('#new_up_vote_link').show();
$('#up_votes').append('<%= j render("up_vote", :up_vote => @up_vote)%>');
views/things/upvote.js.erb
alert("here");
$('#up_votes').html('<%= @new_votes_count %>');
controllers/things_controller.rb
class ThingsController < ApplicationController
def show
@thing = Thing.find(params[:id])
@thing.up_votes.build
@up_vote = UpVote.new
end
def upvote
@thing = Thing.find(params[:id])
UpVote.create!(ip: request.remote_ip, voteable_id: params[:id], voteable_type: 'Thing')
respond_to do |format|
if @up_vote.save
@new_votes_count = @thing.up_votes.count
format.html { redirect_to @thing, notice: 'Voted up' }
format.json { render json: @up_vote, status: :created, location: @up_vote }
format.js
else
@new_votes_count = @thing.up_votes.count
format.html { redirect_to @thing, notice: 'Voted up failed' }
format.json { render json: @up_vote.errors, status: :unprocessable_entity }
format.js
end
end
end
end
private
def thing_params
params.require(:thing).permit(:name, :avatar, :email)
end
end
models/thing.rb
class Thing < ActiveRecord::Base
has_many :up_votes, as: :voteable
# ...
end
models/up_vote.rb
class UpVote < ActiveRecord::Base
belongs_to :voteable, polymorphic: true
end
application.js
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require bootstrap
//= require turbolinks
//= require_tree
routes.rb
#...
post 'things/upvote/:id' => 'things#upvote', as: 'upvote_thing'
resources :things do
resources :up_votes
end
application.js head
<head>
<title>Application</title>
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag "jquery-ui.min" %>
<%= javascript_include_tag "external/jquery/jquery" %>
<%= javascript_include_tag "jquery-ui.min" %>
</head>
See Question&Answers more detail:
os