Ruby on rails:删除用户的投票记录

时间:2015-08-04 21:33:37

标签: ruby-on-rails ruby ajax vote

我在rails应用程序上创建了一个基本的ruby,用户可以在其中投票。他们可以使用ajax方法为引脚投票。

我现在想要的是让用户删除他们的投票。

这是我的实施:

pins_controller.rb:

  def upvote
    @pin = Pin.friendly.find(params[:id])
    @pin.votes.create(user_id: current_user.id)
    respond_to do |format|
    format.html { redirect_to @pin }
    format.js
    end
  end

users_controller.rb

  def upvote
    @pin = Pin.friendly.find(params[:id])
    @pin.votes.create(user_id: current_user.id)
    respond_to do |format|
    format.html { redirect_to @pin }
    format.js
    end
  end

vote.rb

class Vote < ActiveRecord::Base
    belongs_to :user
    belongs_to :pin, counter_cache: true
    validates_uniqueness_of :pin_id, scope: :user_id
end

pin.rb

has_many :votes, dependent: :destroy

在我的观点中,他们可以通过以下方式提出一个引脚:

<% if @pin.votes.where(user_id: current_user.id).empty? %>
  <%= link_to upvote_pin_path(@pin), method: :put, remote: true do %>
    Vote for this pin
  <% end %>
<% else %>
<% end %>

现在我想让用户删除投票记录,但我不知道如何设置它,我试图在我的控制器中创建一个downvote方法,但没有任何效果。

让我走上正轨的任何想法?

1 个答案:

答案 0 :(得分:0)

更多信息会有所帮助。例如,我假设存在某些限制,例如每个投票必须与用户绑定,每个用户每个引脚只有一个投票。但是,解决方案就像

在您的pins_controller.rb

def downvote
   @pin = Pin.friendly.find(params[:id])
   Vote.where(:user_id => current_user.id, :pin_id => @pin.id).each { |v| v.delete }

   respond_to do |format|
     format.html { redirect_to @pin }
     format.js
   end
end

在你的观点中

 <% if @pin.votes.where(user_id: current_user.id) %>
   <%= link_to downvote_pin_path(@pin), method: :put, remote: true do %>
     DELETE your Vote for this Pin!
   <% end %>
 <% else %>
 <% end %>

您可能想为该检查创建便捷方法

在models / pin.rb中

 class Pin
      ...
      def owned?(id)
        self.votes.where(user_id: id).count > 0 ? true : false
      end
 end