0

我终于通过 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 文档中读到,默认情况下,选民只能投票一次。这是否意味着投票支持的用户不能投票反对?我实现的目的是有一个喜欢或喜欢的按钮。

这是我在单击“不喜欢”后从服务器获得的信息:

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方法即可完成此操作。不知道我第一次是怎么错过的。

4

1 回答 1

1

vote_against_vendor中,直接在您调用之后vote_against,您执行以下操作:

render :nothing => true, :status => 404

当您可能应该这样做时:

render :nothing => true, :status => 200
于 2013-09-06T22:19:27.657 回答