开发者

Validates uniqueness of :link

开发者 https://www.devze.com 2022-12-17 04:07 出处:网络
I have a url field named link in my model with the following validation validates_uniqueness_of :link, :case_sensitive => false

I have a url field named link in my model with the following validation

validates_uniqueness_of :link, :case_sensitive => false

When I put "http://stackoverflow.com", it goes well. Now when I put "https://stackover开发者_高级运维flow.com/" (with the trailing slach), this is also accepted as unique. But I want it to be invalid though there is "/" at the last?


I'd suggest that you normalize your URLs (add/strip trailing slash, etc. see http://en.wikipedia.org/wiki/URL_normalization) before storing them in the DB and even before validation.

validates_uniqueness_of :link, :case_sensitive => false
before_validation :normalize_urls

def normalize_urls
  self.link.strip!
  self.link.gsub!(/\/$/,'')
end

This isn't quite what you were asking for but if you don't store normalized URLs, you'll have to query your DB for all possible variations during validation and that could quickly get expensive.


You could always do a custom validator (by using the validate method, for example).

It might look something like this:

class MyModel < ActiveRecord::Base
  validate :link_is_unique

  def link_is_unique
    #Clean up the current link (removing trailing slashes, etc)
    link_to_validate = self.link.strip.gsub(/\/$/,'')

    # Get the current count of objects having this link
    count = MyModel.count(:conditions => ['link = ?', link_to_validate])

    # Add an error to the model if the count is not zero
    errors.add_to_base("Link must be unique") unless count == 0
  end
end

You could then add other logic to clean up the link (i.e. check for http://, www, etc.)


You can customize validations. See this railscast.

0

精彩评论

暂无评论...
验证码 换一张
取 消