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

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
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
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

Lauree Roberts (Guest)
on 2014-04-23 10:42
(Received via mailing list)
As per readme of 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
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) }

*How to ensure validation before saving, to avoid problems of concurrent

For validation you can use uniqueness validation as :

class Driver < ActiveRecord::Base

  validates_uniqueness_of :car_id

This way when any object of Driver is saved it will be checked that
the car_id was taken earlier or not and so the same car_id will not be
assigned to more than one driver.
This topic is locked and can not be replied to.