2015-10-20 50 views
0

根据我的要求,我需要为所有名人投票,但如果我投票支持某个名人,它不应该允许在24小时内为同一个名人投票。如何检查用户是否投票支持名人Rails 4?

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在票表。有人可以帮我从这里出去吗 ?

回答

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 
相关问题