A default flag on a table in rails
I have a simple table/model in rails, vat_rates
. Administrators need to be able to select one, and only one of these as the default rate that will be selected on the HTML form when creating new related items items that have a vat_rate_id
. I have added a boolean default
column to the 开发者_如何学Cvat_rates
table.
What is the most straight forward, and rails-like way to ensure that only one vat_rate
can be the default one at any time?
I'm not really bothered if there are no defaults, just that there are no more than one.
You could add a custom validation method like this and return an error if another vat_rate is selected as default already. Alternatively you can add a before_update or after_update callback like this to set all other default values to false on update.
精彩评论