I have two models (Car and Driver) and a combobox to select which driver belongs to which car. I want the combobox just show the objects that have not yet been associated.
# vehicle
belongs_to: driver # driver
has_one: vehicle # simple_form
# vehicle/_form.html.haml
= f.association: driver, label_method: :name, value_method: :id
How to ensure validation before saving, to avoid problems of concurrent accesses?
Thanks
As per readme of simple_form (https://github.com/plataformatec/simple_form ),
the f.association helper is available with the collection option which accepts the collection of objects that you want to provide for select list.
You can use :
f.association :driver, collection: Driver.unassociated, label_method: :name, value_method: :id
# In Driver model
class Driver < ActiveRecord::Base
scope :unlinked, -> { where(car_id: nil
) }
end
How to ensure validation before saving, to avoid problems of concurrent accesses?
For validation you can use uniqueness validation as :
class Driver < ActiveRecord::Base
validates_uniqueness_of :car_id
end
This way when any object of Driver is saved it will be checked that weather the car_id was taken earlier or not and so the same car_id will not be assigned to more than one driver.
Thanks,
Lauree