user1611237
user1611237

Reputation: 123

rails3 user can only vote once per day

class Rate < ActiveRecord::Base
 attr_accessible :image_id, :rate, :user_id
 belongs_to :image
 belongs_to :user
 validate :user_can_rate_after_one_day

 before_save :default_values

def default_values
 self.rate ||=0
end

protected
  def user_can_rate_after_one_day
    r=Rate.where(:image_id =>image_id, :user_id=> user_id).order("created_at DESC").limit(1)

    if( (Time.now - 1.day) < r[0].created_at)
      self.errors.add(:rate,"you can only vote once per day") 
    else
      return
    end
  end
end

I have one rate model, and i want the user can only rate once per day. i write the user_can_rate_after_one_day method to validte it. If i delete the function, the user can rate many time, if i add this function, user can not rate it. Anyone knows what's wrong here? Thanks

Upvotes: 0

Views: 533

Answers (1)

shreejana
shreejana

Reputation: 391

I have also the same type of problem. I tried to create an application in which a particular user can add standup for the current day only. I wrote the code in my controller create action. The logic is almost similar to your question, but I found one issue in your code due to which your date is not compared properly Time.now - 1.day return in this format 2018-01-22 11:24:23 +0545 and standup[0].created_at return in this format Mon, 22 Jan 2018 08:58:57 UTC +00:00. So, to solve this issue, I converted both the date in same format i.e (Time.now - 1.day).strftime('%F %H:%M:%S') < standup[0].created_at.strftime('%F %H:%M:%S') which returns true, and the code works.

It might be helpful to other viewers as well.

Upvotes: 1

Related Questions