Search code examples
ruby-on-railsactiverecordinner-joinouter-joinjoin

Insert many rows into Join Table Rails


I have 2 Main Tables and a join table. Books, Locations, and BookLocations.

When a book is created It can have many locations, I am trying to find the best way to insert many locations.id into the join table.

def create
  @book = Book.new(book_params)

  if @book.save
   render json: @book, status: :created, location: @book
  else
   render json: @book.errors, status: :unprocessable_entity
  end
end

Say this is the params I am passing to /books

 {
  name: "NewBook",
  locations: ["New York", "Boston", "Toronto"]
 }

To get the locations Id to insert into the join table, do I have to query the locations table and match the names, then insert the ids individually into the join table?

Should this all be done in a loop or is there a better way to go about it?

I really appreciate any advice thank you.


Solution

  • First, I'd suggest that you add an index to location name in case you already don't have one.

    You'll have to query locations, but you don't have to query one by one. You can do something like:

    locations = Location.where(name: params[:locations])

    Or even better, if you can change the params you're passing to pass location ids:

    locations = Location.find(params[:locations])

    And then you can do:

    @book.locations << locations