2015-10-20 79 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 
相關問題