【发布时间】:2014-07-06 14:03:19
【问题描述】:
我的 rails 应用程序中有一个投票系统,允许用户为 Pin 图投票。 但我想限制一个 Pin 只点赞一次的能力。
app/controllers/pins_controller.rb
def upvote
@pin = Pin.find(params[:id])
@pin.votes.create
redirect_to(pins_path)
end
app/models/pin.rb
class Pin < ActiveRecord::Base
belongs_to :user
has_many :votes, dependent: :destroy
has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }
has_attached_file :logo, :styles => { :medium => "300x300>", :thumb => "100x100>" }
end
app/config/routes.rb
resources :pins do
member do
post 'upvote'
end
end
我不确定如何实现这一点,因为我试图实现一个只允许用户投票一次的系统,这不是我想要的,我希望他们能够只投票一次“PIN”。 我知道acts_as_votable gem 提供了这个功能,但由于我没有使用它,我想知道是否有办法在我自己的代码上实现它。
有什么想法吗?
更新:此方法仅允许每个引脚投一票。见@Ege解决方案
让它与这个一起工作:
def upvote
@pin = Pin.find(params[:id])
if @pin.votes.count == 0
@pin.votes.create
redirect_to(pins_path)
else flash[:notice] = "You have already upvote this!"
redirect_to(pins_path)
end
end
【问题讨论】:
标签: ruby-on-rails ruby vote pins