Forum: Ruby on Rails How to has_one/belongs_to association only return the objects unassociated in combobox?

02d7cb10ce5ab149527de331e0950559?d=identicon&s=25 Ricardo do Valle (Guest)
on 2014-04-19 21:33
(Received via mailing list)
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
Eb162fab79de020a461af49c8669d7b0?d=identicon&s=25 Lauree Roberts (Guest)
on 2014-04-23 10:42
(Received via mailing list)
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 modelclass 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
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.