我有两个型号(Car和Driver)和一个组合框来选择哪个司机属于哪个车。我希望组合框只显示尚未关联的对象。
# vehicle
belongs_to: driver
# driver
has_one: vehicle
# simple_form
# vehicle/_form.html.haml
= f.association: driver, label_method: :name, value_method: :id
您可以为关联输入提供自己的集合,例如:
= f.association :driver, label_method: :name, value_method: :id, collection: Driver.not_assigned_to_a_vehicle
如果您在Driver
上还没有返回所有没有Vehicle
的驱动程序的作用域,则需要添加一个:
class Driver < ActiveRecord::Base
...
scope :not_assigned_to_a_vehicle, -> { joins("LEFT OUTER JOIN vehicles ON vehicles.driver_id = drivers.id").where(vehicles: { id: nil }) }
...
end