如何检查用户是否在 24 小时前投票 rails 4

How to check if a user has voted before 24hrs rails 4

我需要检查用户是否在 24 小时之前投票,如果是,我需要允许他投票

if current_user.vote = true
  if @vote.updated_at > Time.now - 24.hours          
    @vote.save          
  end
end

但我收到错误信息 nil:NilClass 的未定义方法“>” 那么我该如何解决这个问题?

根据您的问题和您的代码块,以下是您的代码问题

if current_user.vote = true ## This always return true so you should have `current_user.votes.present?`
  if @vote.updated_at > Time.now - 24.hours ## @vote object is blank instaed it should be `current_user.votes.last.updated_at < Time.now - 24.hours`
    @vote.save          
  end
end

所以尝试这样改变:

if current_user.votes.present?
  if current_user.votes.last.updated_at < Time.now - 24.hours
    @vote.save          
  end
end

考虑@vote 是你的新对象