views:

20

answers:

1

What is an efficient and elegant way of performing a "find_or_create_all" in rails?

Given:
names = ["Bob","John","Jack","Sid"],
Users table

Needed:
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.

A: 

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.

Geoff Lanotte
Sid
If the order is random and you want to keep it in the same random order, I don't know of a good way. If there is some order based on a database table you can use `User.find(:conditions => {:name => names}, :order => column_name)`. Or after the fact with sort_by http://ruby-doc.org/core/classes/Enumerable.html#M003120.
Geoff Lanotte
I would also check your database documentation to see if you can do something there by writing you own SQL.
Geoff Lanotte