Find or Create Multiple Records in Ruby on Rails - "find_or_create_all"
What is an efficient and elegant way of performing a "find_or_create_all" in rails?
Given:
names = ["Bob","John","Jack","Sid"], Users tableNeeded:
users = ["#User:0x3ae3a00", "#User:0x3ae3938", "#User:0x3ae3898", "#User:0x3ae37f8"]where a user is created only if it doesn't exist.
An intermediate solution - ["#User:0x3ae3a00", nil, nil, "#User:0x3ae37f8"] will also do, if for example only the开发者_运维知识库 first and fourth entries exist in the Users table.
One way is to use a find_all_by_name and use a hash to map back to the entries in the names array but I wonder if there is an elegant yet efficient way in rails.
ar_extensions provides a good solution. https://github.com/zdennis/ar-extensions
Assuming the table in question has a column with a unique database index, bulk inserts can be used to insert if there isn't a match on the unique column and skip or update the row if there is a match on the unique column.
Loading large datasets at envycasts covers this case http://envycasts.com/products/advanced-activerecord
If I understand and you want to take an array of names and convert it into an array of users?
names = ["Bob","John","Jack","Sid"]
users = names.map{|name| User.find_or_create_by_name(name)}
that will return an array of user objects.
In Rails 6 there is now upsert_all which I think handles this super well.
Book.upsert_all([
{ title: "Rework", author: "David", isbn: "1" },
{ title: "Eloquent Ruby", author: "Russ", isbn: "1" }
], unique_by: :isbn)
精彩评论