What is the .build method?

In Ruby on Rails, the .build method is used within the context of Active Record associations to create a new associated object in memory. It’s particularly helpful when working with nested forms in your Rails application.

In simple words, the build method is a way to create a new item (or record) that is connected to another item without immediately saving it to the database.

Key Points

  • .build creates a new object in memory, but it doesn’t save it to the database.
  • It’s often used with forms to pre-populate associated fields and simplify form submission.
  • The new object is linked to the parent object through the foreign key, but the association isn’t persisted until you explicitly save both objects.

Example Scenario

There is a blog website. On this website:
-> We have Users who write Articles.
In our code, a User can have many Articles.

How build Works

1. Find the User: We will first find the user who will write the article.
2. Create the Article: We will use the build method to create a new article for that user. This article has all the information it needs to be connected to that user, but it’s not saved to the database yet.
3. Save the Article: When we’re ready, we will save the article to the database.

Why Use build?

  • Associations: It automatically connects the new article to the user.
  • Delay Saving: We can set up everything we need before actually saving it to the database.

How to Use build

In the Rails Console-

1. Find the User:
user = User.find(1)

2. Build the Article:
article = user.articles.build(title: “New Article”, content: “This is my first Article”)

  • user.articles.build creates a new article connected to user.
  • The article is not saved yet.

3. Save the Article:
article.save

In the Controller-

When we have a form on our website to create a new article, we can use build in the controller to handle this:

1. New Action: Set up the form with a new article connected to a user.

def new
@user = User.find(params[:user_id])
@article = @user.articles.build
end

2. Create Action: Handle form submission and save the article.
We will create a create method to handle the submission

def create 
@user = User.find(params[:user_id]) 
    @article = @user.articles.build(article_params) 
if @article.save 
redirect_to @article, notice: 'Article was successfully created.' 
else
render :new end 
end
end

Summary

By effectively using the .build method, we can streamline the creation of associated objects in our Rails applications and provide a seamless user experience for nested forms.

Support On Demand!

Ruby on Rails