Validate uniqueness within a recent set

Posted by Matchu on Stack Overflow See other posts from Stack Overflow or by Matchu
Published on 2010-05-13T01:47:53Z Indexed on 2010/05/13 1:54 UTC
Read the original article Hit count: 340

Is there a standard Rails 3 way of detecting uniqueness within a particular scope, or is this custom validation all I can do?

class Post < ActiveRecord::Base
  # [named scope for recent posts]

  validates do |post|
    if Post.recent.where('url = ?', post.url).count > 0
      errors[:url] = 'has already been posted recently - thanks anyway!'
    end
  end
end

(Haven't yet tried that exact code, so there may be errors, but you get the idea.)

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby-on-rails3