[Rails] How to has_one/belongs_to association only return the objects unassociated in combobox?

46 views
Skip to first unread message

Ricardo do Valle

unread,
Apr 19, 2014, 3:31:02 PM4/19/14
to rubyonra...@googlegroups.com

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

Lauree Roberts

unread,
Apr 23, 2014, 1:39:26 AM4/23/14
to rubyonra...@googlegroups.com

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
Reply all
Reply to author
Forward
0 new messages