Question

I have a user database, it has Company column, it can be empty i.e null or may contain some value. But if contains any value, it should be unique. If I use the unique attribute in my model it is not allowing to have multiple null values for the column. I am using Sqlite3 db.

Was it helpful?

Solution

You could use a Model validation to handle it. Perhaps something like this:

class User < ActiveRecord::Base
  attr_accessible :company

  validate do
    if self.company && User.where(company: self.company).first
      raise ArgumentError, "Company must be `nil` or unique"
    end
  end
end

It's a bit of a hack, but it should fit your needs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top