如何检查用户是否已投票选举名人Rails 4?

时间:2015-10-20 05:58:49

标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-3.2

根据我的要求,我需要为所有名人投票,但如果我投票给某个名人,则不应该允许在24小时内为同一个名人投票。

Vote.rb

class Vote < ActiveRecord::Base
attr_accessible :celebrity_id, :user_id

belongs_to :user
belongs_to :celebrity, counter_cache: true
end

Celebrity.rb

class Celebrity < ActiveRecord::Base
attr_accessible :name, :gender, :category_id, :image, :votes_count
validates_presence_of :name
belongs_to :user
belongs_to :category
has_many :votes
end

我的控制器:

def vote
@celebrities = Celebrity.find(params[:id])
if current_user.votes.present?
  if current_user.votes.last.updated_at < Time.now - 24.hours
    @vote = current_user.votes.build(celebrity_id: @celebrities.id, :id => params[:vote])        
    @vote.save
  end
  respond_to do |format|
    format.html { redirect_to ranking_screen_url }
    format.json { render json: @vote, status: :created }
  end
else
  @vote = current_user.votes.build(celebrity_id: @celebrities.id, :id => params[:vote])     
  @vote.save
  respond_to do |format|
    format.html { redirect_to ranking_screen_url }
    format.json { render json: @vote, status: :created }
  end
end
end

而不是检查current_user.votes.present?我需要检查用户是否已在投票表中投票选出了celebrity_id。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

if current_user.votes.present?

在这里,您要检查用户是否进行了投票。我认为你应该取得特定名人的用户投票。像

@celebrity = Celebrity.find(params[:id])
@vote = current_user.votes.where(celebrity_id: @celebrity.id).first

if @vote
  if @vote.updated_at < (Time.now - 24.hours)
    # update count here
  else
else

end