Reputation: 309
I have a model named "Cars"
I wonder how I can declare in the model, so that only one record can exist when two attributes match each other. For example, in the Car Model
:owner_id, :driver_id
Let's say a record exists:
:id => "1", :owner_id => "22", :driver_id => "23", :state => "parked"
If I try to create another record, that also had the same owner_id
and driver_id
that matched each other, the record would not be able to create itself. I am trying to make a relation model that will create one record for each owner and driver, when they are matched.
Upvotes: 1
Views: 1349
Reputation: 16092
In your Car
model you can define a validation:
validates :driver_id, uniqueness: { scope: :owner_id }
I believe this should give you the intended behavior, there will be a validation error if you try creating another car with the same driver and owner.
Upvotes: 8