我终于通过ajax正确提交了我的投票,但我似乎“似乎没有投票”。这是我的模特:
class User < ActiveRecord::Base
acts_as_voter
end
class Vendor < ActiveRecord::Base
acts_as_voteable
end
我的路线:
resources :vendors do
collection do
post :vote_for_vendor
delete :vote_against_vendor
end
end
我的控制器:
class VendorsController < ApplicationController
def vote_for_vendor
begin
vendor = Vendor.find(params[:vendor_id])
current_user.vote_for(vendor)
render :nothing => true, :status => 200
rescue ActiveRecord::RecordInvalid
render :nothing => true, :status => 404
end
end
def vote_against_vendor
begin
vendor = Vendor.find(params[:vendor_id])
current_user.vote_against(vendor)
render :nothing => true, :status => 404
rescue ActiveRecord::RecordInvalid
render :nothing => true, :status => 404
end
end
end
我的观点:
<table class="table table-condensed table-hover">
<tr>
<th>Name</th>
<th>Address</th>
<th>Favorite?</th>
</tr>
<% @vendors.each do |v| %>
<tr>
<td><%= v.name %></td>
<td><%= v.address %></td>
<td id="toggle">
<% if current_user.voted_for?(v) %>
<%= button_to "Unlike", { :controller => :vendors, :action => 'vote_against_vendor', :vendor_id => v.id},
{ :method => 'delete', :remote => true }%>
<% else %>
<%= button_to "Like", { :controller => :vendors, :action => 'vote_for_vendor', :vendor_id => v.id},
{ :method => 'create', :remote => true} %>
<% end %>
</td>
</tr>
<% end %>
</table>
那么我怎样才能为供应商投票呢?我在thumbs_up文档中读到,默认情况下,选民只能投票一次。这是否意味着vote_for的用户不能再为vote_against?我实现的目的是拥有一个喜欢或喜欢的按钮。
这是我点击'不喜欢'后从服务器获得的内容:
Started DELETE "/vendors/vote_against_vendor?vendor_id=1" for 127.0.0.1 at 2013-09-06 14:34:02 -0700
Processing by VendorsController#vote_against_vendor as JS
Parameters: {"authenticity_token"=>"/ZdePkPe+4rM8thUa+81hEL68cw1CJn93P0LQqEMC3s=", "vendor_id"=>"1"}
Vendor Load (0.2ms) SELECT "vendors".* FROM "vendors" WHERE "vendors"."id" = ? LIMIT 1 [["id", "1"]]
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
(0.1ms) begin transaction
Vote Exists (0.2ms) SELECT 1 AS one FROM "votes" WHERE ("votes"."voteable_id" = 1 AND "votes"."voteable_type" = 'Vendor' AND "votes"."voter_type" = 'User' AND "votes"."voter_id" = 1) LIMIT 1
(0.1ms) rollback transaction
Rendered text template (0.0ms)
Completed 404 Not Found in 7ms (Views: 0.6ms | ActiveRecord: 0.7ms | Solr: 0.0ms)
专业提示:在你看起来很傻之前,请仔细阅读文档,然后问一个愚蠢的问题。只需使用unvote_for
方法即可完成此操作。不确定我第一次错过了它。
答案 0 :(得分:1)
在vote_against_vendor
中,在您致电vote_against
后直接执行此操作:
render :nothing => true, :status => 404
当你应该这样做时:
render :nothing => true, :status => 200