Active Record: find_or_create_by with additional attributes

Updated . Posted . Visible to the public.

Say you want to fetch a record like a user with a particular nick name and if no user with the specified name exists, create one with certain additional attributes like email or full name.
The ActiveRecord query method find_or_create_by takes care of finding or creating a record given an attribute, in order to create the record with the additional attributes without a second trip to the database, however, we can make use of create_with like so:

attributes = {full_name: "Mr. Wombat", email: "womb@bat.com"}
User.create_with(attributes).find_or_create_by(nick_name: "wombi")

Alternative we can pass a block to find_or_create_by:

User.find_or_create_by(nick_name: "wombi") do |r|
  r.full_name = "Mr. Wombat"
  r.email = "wom@bat.com"
end
Jan Bussieck
Last edit
Jan Bussieck
Posted by Jan Bussieck to 9elements's deck (2015-06-04 13:58)