mardi 21 juin 2016

How to use validates_uniqueness_of an id but only for some items out of a list of items with the same id. rails

I have two drop down lists. One that contains items with bmp_id and a sublist that includes items with that bmp_id (in this case it is 2) that each have a unique bmpsublist_id. One of the options from the main dropdown list includes five sublist options with the bmpsublist_id's [3, 4, 5, 6]. I want to make it so that the user can only have ONE of the sublist choices with bmpsublist_id's [4, 5, and 6] the bmpsublist_id should not be unique and would be able to be added regardless of whether the others have been added. When you submit the form, the bmp_id and bmpsublist_id are added to a table called Bmp.

This is the validation I'm using in my model:

validates_uniqueness_of :bmp_id, :message => "TODO", if: "bmpsublist_id == 4 || bmpsublist_id == 5 || bmpsublist_id == 6 || bmpsublist_id == 7"

The issue with this validation is that if you add option with bmpsublist_id 3 first, you can no longer add those with bmpsublist_id's of 4, 5, and 6 which I want to still be able to add one even if a record with bmpsublist_idof 3 has already been added. But if you add one of the ones with bmpsublist_id's of 4, 5, or 6, you can still add the one with 3 which I don't want to change.

Any ideas? Sorry if this is super confusing. I don't really know how to explain things very well.

UPDATE:

I figured it out, answer is below

Aucun commentaire:

Enregistrer un commentaire