简体   繁体   English

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

[英]Ruby on rails: delete a vote record by user

I created a basic ruby on rails apps where users can vote for a pin. 我在Rails应用程序上创建了一个基本的红宝石,用户可以在其中投票给大头针。 They can vote for a pin using an ajax method. 他们可以使用ajax方法投票给别针。

What I want now is to let users delete their vote. 我现在想要的是让用户删除其投票。

Here is my implementation: 这是我的实现:

pins_controller.rb: 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 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 pin.rb

has_many :votes, dependent: :destroy

in my views, they can upvote a pin through this: 在我看来,他们可以通过以下方式对图钉进行投票:

<% 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 %>

Now I would like to let users delete a vote record, but I am not sure how I can set this up, I tried to create a downvote method in my controllers, but nothing worked. 现在,我想让用户删除投票记录,但是我不确定如何设置它,我试图在控制器中创建一个downvote方法,但是没有任何效果。

Any ideas to put me on track ? 有什么想法可以使我步入正轨吗?

More information would be helpful. 更多信息会有所帮助。 For example, I am assuming there are some sorts of restrictions, such as every vote has to be tied to a user and only one vote per pin per user. 例如,我假设存在某种限制,例如每个投票都必须绑定到一个用户,并且每个用户每个销钉只能投票一个。 However, the solutions is something like 但是,解决方案类似于

In your pins_controller.rb 在您的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

And in your views 在你看来

 <% 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 %>

You probably want to create a convenience method for that check 您可能想为该检查创建一种便捷方法

In models/pin.rb 在models / pin.rb中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM