Domanda

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.

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top