对于Rails还是很新的。我使用acts_as_votable gem创建了upvote和upvote按钮,以允许用户对视频进行upvote / downvote,但是我无法使它们从upvote / downvote更改(反之亦然),并且每次单击时都更新计数器,而无需刷新页面。我尝试遵循其他类似的答案,但是没有运气。这是我尝试实现的。
index.html.erb
<% @videos.each do |x| %>
<p> <div class="child">
<video controls width="310" height="230" src="<%= x.file %>"></video>
<div class="btn-group">
<%= link_to upvote_video_path(x), method: :put, remote: :true, id: "like-count", class: "btn btn-default btn-sm" do %>
<span class="glyphicon glyphicon-chevron-up"></span>
Upvote
<div id="video-<% x.id %>"> <%= x.get_upvotes.size %> </div>
<% end %>
<% end %>
</div>
</div>
<%= x.title %>
</div> </p>
<% end %>
upvote.js.erb(位于视频视图文件夹中)
$("#video-<%= x.id %>").html('<%= x.get_upvotes.size %>');
def upvote
@video = Video.find(params[:id])
@ip = request.remote_ip
was_it_upvoted = Ipaddresstracker.find_by(ipaddress: @ip, videoid: @video.id)
if was_it_upvoted
@video.downvote_by User.first
was_it_upvoted.delete
else
Ipaddresstracker.create(:ipaddress => @ip, :videoid => @video.id)
@video.vote_by voter: User.first, :duplicate => true
end
respond_to do |format|
format.html { redirect_back fallback_location: root_path }
format.json { render layout:false }
end
路线
resources :videos do#, only: [:index, :show] do
member do
put "upvote", to: "videos#upvote"
put "downvote", to: "videos#downvote"
end
end
application.js
//= require introjs
//=require rails-ujs
//= require turbolinks
//= require_tree .
application.html.erb(头标记)
<head>
<title>Workspace</title>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>