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.
Asked
Active
Viewed 140 times
-1
-
Duplicate of: http://stackoverflow.com/questions/191421/how-to-create-a-unique-index-on-a-null-column – forker Jun 24 '13 at 16:09
-
how can i do it in ruby on rails ? – Hrishikesh Sardar Jun 24 '13 at 16:13
1 Answers
0
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.

Eugene
- 4,829
- 1
- 24
- 49
-
`User.where(company: self.company).exists?` might be a better approach than `first`. – mu is too short Jun 24 '13 at 16:43
-
What if i make a function of this, and I want to run it everytime a new user is created. so how will do that ? – Hrishikesh Sardar Jun 24 '13 at 16:52
-
`validates` will run every time a `User` is created or updated, there is no need to create a separate method for it. – Eugene Jun 24 '13 at 16:53
-
I think its running on every page and I am getting this error "You need to supply at least one attribute" – Hrishikesh Sardar Jun 24 '13 at 16:56
-
I figured it out i changed "validates" to "validate". Thanks a lot guyz for your help. I really appreciate it ! – Hrishikesh Sardar Jun 24 '13 at 17:00
-