In Ruby on Rails, create is a method provided by the Active Record class that allows us to create and save new records to the database in a single step. In this blog, we'll take a closer look at how to use create, as well as some of its variations and options.

Basic Usage

        The simplest way to use create is to call it on the model class, passing in a hash of attributes to set for the new record:

user = User.create(name: 'John Doe', email: 'john@example.com')

This will create a new User record with the specified name and email attributes, and save it to the database. If the record is successfully saved, create will return the newly created record.

Handling Errors

        If the record fails to save due to validation errors or other issues, create will raise an exception. To handle errors gracefully, we can use the create! method instead, which behaves the same as create but raises a RecordInvalid exception instead of returning nil:

begin
  user = User.create!(name: '', email: 'john@example.com')
rescue ActiveRecord::RecordInvalid => e
  puts e.message
end

        In this example, we're attempting to create a User record with a blank name attribute, which will fail validation. By using create!, we can catch the resulting exception and handle the error as needed.

Finding or Creating

        Sometimes we want to create a new record only if it doesn't already exist in the database. For example, we might want to create a new User record for a new email address, but use an existing record if the email address already exists. We can use the find_or_create_by method to accomplish this:

user = User.find_or_create_by(email: 'john@example.com') do |u|
  u.name = 'John Doe'
end

        This will attempt to find a User record with the specified email attribute, and if one is not found, it will create a new record with the specified name and email attributes. If a matching record is found, the existing record will be returned instead of creating a new one.

Creating Through Associations

        In Rails, we can create new records through associations between models. For example, if we have a User model that has_many Post records, we can create a new Post record for a specific user using the create method on the Post model, passing in the User object:

user = User.first
post = user.posts.create(title: 'New post', body: 'This is a new post.')

        This will create a new Post record with the specified title and body attributes, and associate it with the specified User object. The user_id attribute on the new Post record will be set to the ID of the User object.

Mass Assignment Security

        By default, Rails will allow any attribute to be set through mass assignment when using create. However, this can be a security risk, as an attacker could potentially set attributes that they shouldn't have access to. To prevent this, we can use the attr_accessible or attr_protected methods in our model to specify which attributes can be set through mass assignment. For example:

class User < ActiveRecord::Base
  attr_accessible :name, :email
end

        This will allow the name and email attributes to be set through mass assignment when creating or updating a User record, but any other attributes will be ignored.

Multiple Records

        The create method can also be used to create multiple records at once. To do this, we can pass an array of attribute hashes to create, like so:

users = User.create([{ name: 'John Doe', email: 'john@example.com' }, { name: 'Jane Doe', email: 'jane@example.com' }])

        This will create two new User records with the specified attributes, and return an array of the newly created records.

Custom Primary Key

        If our model uses a custom primary key column instead of the default id column, we can use the create method with the :primary_key option to specify the value of the custom primary key. For example:

class User < ActiveRecord::Base
  self.primary_key = 'uuid'
end

user = User.create(name: 'John Doe', email: 'john@example.com', uuid: 'abc123')

        This will create a new User record with the specified name, email, and uuid attributes, and set the custom primary key to 'abc123'.

Conclusion

        The create method in Rails provides a simple and powerful way to create and save new records to the database. By using create!, we can handle errors gracefully and ensure that our data is consistent and valid. The find_or_create_by method allows us to create new records only when necessary, while the ability to create records through associations makes it easy to manage related data in our application.