Rails create or update magic?-open source projects miniMAC/magic

Mohamad

You can use: find_or_initialize or find_or_create

For example, in Rails 4 syntax:

user = User.find_or_initialize_by(name: "Roger")
user.update(name: "Elmer")

Alternatively:

user = User.where(name: "Roger").first_or_initialize

Rails 3:

user = User.find_or_initialize_by_name("Roger")
user.update_attributes(name: "Elmer")

If the record is newly initialised update or update_attributes will attempt to save it.

Both forms accept a block:

User.find_or_initialize_by(name: "Roger") do |user|
  user.name = "Elmer"
  user.save
end

User.where(name: "Roger").first_or_initialize do |user|
  user.name = "Elmer"
  user.save
end

Documentation can be found on api.rubyonrails.org.