Reputation: 26192
I'm working on a ruby on rails app and I want to put constraint on more than one field in database table i.e :
|id|field_one|field_two
1 27 Value
2 27 Value
This should be illegal because combination of field_one and field_two should not repeat. This below is perfectly fine :
|id|field_one|field_two
1 27 Value
2 28 Value
3 27 AnotherValue
Can I make this constraints at database level? Or I need to do it in my ruby class level?
Upvotes: 2
Views: 126
Reputation: 54882
Yes, you can do it with a regular validates, uniqueness and scope options:
validates :field_one, uniqueness: { scope: [:field_two] }
If you want your own custom validation method, you can do this:
validates :uniqueness_of_fields
private # optionnal
def uniqueness_of_fields
if self.class.exists?(field_one: self[:field_one], field_two: self[:field_two])
self.errors.add(:field_one, "Combination #{self[:field_one]} and #{self[:field_two]} already existings!"
logger :do_your_thing # here is where you want to log stuff
return false
else
return true # validation passes, is unique
end
end
Upvotes: 3
Reputation: 27779
Yes, you can do this as a database constraint. In a migration:
add_index :table_name, [:column_name_a, :column_name_b], unique: true
Upvotes: 2