I have this table associating airlines with rental cars. It has four
columns - user_id, airline_id, rentalcar_id and id. I need to make sure
that the combo of airline_id and rentalcar_id is always unique - in
other words, a user cannot have two fields with the same airline_id and
rentalcar_id. Is this done with one of the validation commands in the
model? I have look at the one that I can find and none seems to fit all
that well. Thanks,
I have this table associating airlines with rental cars. It has four
columns - user_id, airline_id, rentalcar_id and id. I need to make sure
that the combo of airline_id and rentalcar_id is always unique - in
other words, a user cannot have two fields with the same airline_id and
rentalcar_id. Is this done with one of the validation commands in the
model? I have look at the one that I can find and none seems to fit all
that well. Thanks,
Create a unique index on user_id, airline_id, rentalcar_id in your
migration… that would be one way
Whichever is the widest scope (e.g., can an airline have a lot of
rental cars? Or the other way around?) should probably go with
:scope. I don’t think it would affect anything, but for modeling’s
sake it should be that way.
I second that. I’m using validates_uniquemess_of with :scope for the
same purpose in one of my projects. In the testing I have done it did
not matter which one went in the :scope. I agree that the widest
would be the better choice for readability later.
What I was trying to do was to have a user with an airline membership be
associated to as many rental car companies as they desired, but to
insure the integrity of the database, I didn’t want an entry that had
all three columns the same - user_id, airline_id, and rentalcar_id. The
same user_id and airline_id was ok as long as they all had different
rentalcar_id’s. Hope this makes some sense, because it was confusing the
hell out of me. Anyway, here is what I did:
validates_uniqueness_of :rentalcar_id, :scope => :airline_id and
:_user_id
and it seems to work. I didn’t know that I could say and but apperently
I can. Thanks all,
I second that. I’m using validates_uniquemess_of with :scope for the
same purpose in one of my projects. In the testing I have done it did
not matter which one went in the :scope. I agree that the widest
would be the better choice for readability later.