Vinoth Kannan

TIL - Today I Learned

Pluck a column of an Array by index in RoR

I know you already aware of the support of the pluck method in RoR and ActiveRecord. Using it you can pluck the values of an array column (or a table column) by its name.

Recently I discovered that we can pluck the column by its index too. It won’t work in the ActiveRecord. Since it supports neither array of hashes nor an array of objects. But you can use it in the array of arrays like in the below example.

arr = [
        ["Foo1", "Bar1", "1", "W"],
        ["Foo2", "Bar2", "2", "X"],
        ["Foo3", "Bar3", "3", "Y"],
        ["Foo4", "Bar4", "4", "Z"]
=> ["1", "2", "3", "4"]

We can achieve the same using method too.

Bulk Insert support in ActiveRecord – RoR 6

Now Rails 6 have support to bulk insert data using ActiveRecord . You should pass an array of hashes into the insert_all method (like the below example) to insert multiple rows in a single SQL query.

  { id: 1, title: "Rework", author: "David" },
  { id: 2, title: "Eloquent Ruby", author: "Russ" }

Also, it will skip duplicate records in the array by default.

# Insert records and skip inserting any duplicates.
# Here "Eloquent Ruby" is skipped because its id is not unique.

  { id: 1, title: "Rework", author: "David" },
  { id: 1, title: "Eloquent Ruby", author: "Russ" }

And it is supporting the bang (!) operator too ( insert_all! ).