Commando
Commando

Reputation: 358

How to save Join Table with Ruby on Rails

I'm trying to create a simple app that lets the user save a driver, save a car and combine them (by a join table).

Driver model:

has_many :cars_drivers
has_many :cars, through: :cars_drivers

Car model:

has_many :cars_drivers
has_many :drivers, through: :cars_drivers

cars_driver model:

belongs_to :car, optional: true
belongs_to :driver, optional: true

I wanted to show all cars that the driver has been on so I added this on the drivers_controller:

def create
  @driver = Driver.new(driver_params)
  respond_to do |format|
    if @driver.save
      CarsDriver.where(driver_id: @driver.id).destroy_all
        form_cars_selected.each do |car_id|
          CarsDriver.create driver_id: @driver.id, car_id: car_id
        end
      format.html { redirect_to @driver, notice: 'Driver was successfully created.' }
      format.json { render :show, status: :created, location: @driver }
    else
      format.html { render :new }
      format.json { render json: @driver.errors, status: :unprocessable_entity }
    end
  end
end

and this is on the view:

<% if @driver.cars.blank? %>
  Driver has no cars.
<% else %>
  <%= @driver.cars.pluck(:description).to_sentence %>
<% end %> 

But it doesn't work. What could I miss? Is there any easier way to set this basic relation in RoR?

Upvotes: 0

Views: 87

Answers (1)

PGill
PGill

Reputation: 3521

in new/edit Driver form you can add a multi select

<%= form.select :car_ids, Car.order(:name).map { |c| [c.name, c.id] }, {}, multiple: true %>

in the controller allow car_ids: [] to patient_params

This way you can add cars to a Driver from Driver form


_ids= is a special method that lets you create joins model

Upvotes: 1

Related Questions