class Rating < ActiveRecord::Base belongs_to :rateable, :polymorphic => true validates_presence_of :rateable_type, :rateable_id validates_numericality_of :value validate :maximum_value_is_not_breached before_save :delete_last_rating def self.find_similar(rating) Rating.find( :first, :conditions => { :ip_address => rating.ip_address, :rateable_id => rating.rateable_id, :rateable_type => rating.rateable_type } ) end protected def maximum_value_is_not_breached errors.add('value', 'is not in the range') unless rateable.rating_range.include?(value) end def delete_last_rating if (rating = Rating.find_similar(self)) rating.destroy end end end