Inserting Records in Rails using a Relation

Say you have a Rails app where you have 2 tables and a join table between them. If you want to insert records into the join table, generally you’ll create tuples of table_a_id and table_b_id, but for large inserts this can be inefficient, especially when table_a might only have a few records in the tuple and table_b has many. Luckily with the help of ARel, we can insert records from a subquery (ActiveRecord Relation).

29 Dec 2022