문제

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.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top