Piccolo
Piccolo

Reputation: 1666

How do you add a custom uniqueness validation to an ActiveRecord model in Rails?

I was perusing the Ruby on Rails Guides article on ActiveRecord validations and I came across this neat excerpt about the uniqueness validation:

There is also a :case_sensitive option that you can use to define whether the uniqueness constraint will be case sensitive or not. This option defaults to true.

This is a very useful feature to ensure that two users can't sign up with the same username or email, for example. However, I want to use a similar validation but with a different method of determining the strings' equality. I want to make sure that all of my entries are unique under squeeze.

As an example, say my Post model has a text property content. I want to make sure that if foo bar is already in the database, it will not accept foo bar or foo bar. Is there a better way of doing this than just adding a custom validation to iterate over Post.all, squeezeing each entry, and comparing it to the squeezed content? I can't imagine that scales well.

Upvotes: 0

Views: 1073

Answers (2)

m. simon borg
m. simon borg

Reputation: 2575

You can add another column to your posts table called squeezed_content or something like that, then do something like this to use a built in uniqueness validation:

class Post < ActiveRecord::Base
  before_save :set_squeezed_content
  validates :squeezed_content, uniqueness: true

  def set_squeezed_content
    self.squeezed_content = content.squeeze
  end
end

Upvotes: 3

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

While you might try to accomplish everything in “Rails” way, in this particular case I would go another path. If for some reason you want to keep “foo        bar” content in the database, just introduce a new field squeezed_content, implement a post_commit hook to update this field with a squeezed value of content and imply a validation on that newly introduced squeezed_content field enforcing it to be unique.

Also you might just store already squeezed values.

Upvotes: 2

Related Questions