When working with ActiveRecord associations in Ruby on Rails, you might come across two seemingly similar methods: build and new. While these methods serve the same purpose; creating new instances of associated objects; developers often wonder when to use one over the other. In this article, we'll explore these methods, their differences (or lack thereof), and best practices for their usage.
The Key Takeaway (TL;DR)
There is no functional difference between build and new when working with ActiveRecord associations. The build method is simply an alias for new in the context of associations. Your choice between them is purely about readability and code style, not behavior.
The Basics: What Are build and new?
Both build and new are methods used to create a new instance of an associated object without saving it to the database. They allow you to initialize an object with attributes and set up the association automatically by assigning the foreign key.
For example, consider a User model that has many Community objects:
class User < ApplicationRecord
has_many :communities
end
class Community < ApplicationRecord
belongs_to :user
end
To create a new Community associated with a User (e.g., current_user), you can use either:
community = current_user.communities.build(name: "Tech Enthusiasts")
community = current_user.communities.new(name: "Tech Enthusiasts")
Both methods achieve the same result: they initialize a Community object with the user_id set to current_user.id and the name attribute set to "Tech Enthusiasts".
The Full Picture: new, build, and create
Before diving deeper, it's helpful to understand the complete landscape of object creation methods in Rails:
- new / build: Create an unsaved instance (must call save to persist)
- create: Creates and immediately saves the instance to the database
# These create unsaved instances
community = current_user.communities.build(name: "Tech Enthusiasts")
community = current_user.communities.new(name: "Tech Enthusiasts")
community.persisted? # => false
# This creates and saves in one step
community = current_user.communities.create(name: "Tech Enthusiasts")
community.persisted? # => true
This article focuses on the first two methods, which are functionally identical.
build vs new: Technical Differences
From a technical perspective, there is no functional difference between build and new when used with ActiveRecord associations. In fact, the build method is simply an alias for new in the context of associations.
Both methods:
- Create an unsaved instance of the model
- Automatically set the foreign key (user_id in this example) based on the association
- Return the new object without persisting it to the database
Where Each Method Works
An important distinction to understand is where each method is available:
- build: Only available on association collections (e.g., current_user.communities.build)
- new: Available both on associations AND directly on model classes (e.g., Community.new)
# These work (on associations)
current_user.communities.build(name: "Tech Enthusiasts")
current_user.communities.new(name: "Tech Enthusiasts")
# These work (on model classes)
Community.new(name: "Tech Enthusiasts", user_id: current_user.id)
# This DOESN'T work
Community.build(name: "Tech Enthusiasts") # NoMethodError!
This is why build exists: it's specifically designed for the association context, where it reads more naturally in English ("build a community" rather than "new a community").
When to Use build or new
Although both methods work identically on associations, the choice between them often comes down to personal preference and readability. Here's a breakdown of scenarios to help you decide:
1. Use build for Clarity in Associations
If you're working with associations, using build makes it clear that the new object is part of a relationship. This can be particularly helpful for readability in complex codebases or when collaborating with other developers.
community = current_user.communities.build(name: "Tech Enthusiasts")
In this example, it's immediately obvious that the Community being created is associated with current_user.
2. Use new for General Object Creation
If you're more familiar with new or prefer the consistency of using a single method across your codebase, it's perfectly fine to use new. Since new is more widely used in Rails (and works everywhere), some developers prefer it for uniformity.
community = current_user.communities.new(name: "Tech Enthusiasts")
3. Nested Forms or Dynamic Association Building
In scenarios like nested forms, where you dynamically build associated objects, developers often prefer build to emphasize the association's role.
@user = User.find(params[:id])
@user.communities.build(name: "Tech Enthusiasts")
Here, build makes it clear that the Community is part of the User.
What Happens Behind the Scenes?
When you call build or new on an association, Rails performs the following actions:
- Creates a New Object: A new instance of the associated model (e.g., Community) is initialized
- Sets the Foreign Key: The foreign key (user_id) is automatically set to the ID of the parent object (current_user in this case)
- Does Not Persist the Object: The object is not saved to the database until you explicitly call save
For example:
community = current_user.communities.build(name: "Tech Enthusiasts")
community.user_id # => current_user.id
community.persisted? # => false
community.save # Saves the object to the database
community.persisted? # => true
Best Practices
- Use build for Association-Specific Contexts: If you're working within the context of a parent-child relationship, prefer build for better readability and clarity
- Be Consistent: Consistency in your codebase is more important than the specific method you choose. Whether you use build or new, stick to one approach across your project to avoid confusion
- Understand the Database State: Remember that neither method saves the object to the database. If you need to persist the object immediately, use create instead
- Choose Based on Team Preference: Since there's no technical difference, align with your team's conventions or style guide
Conclusion
In Ruby on Rails, build and new are essentially interchangeable when working with ActiveRecord associations, they're literally the same method under the hood. The choice between them is purely a matter of personal or team preference and code readability.
If you value clarity and natural language in association contexts, build might be the better choice. On the other hand, if you prefer uniformity and the flexibility of a method that works everywhere, new works just as well.
Ultimately, both methods are tools to help you create associated objects efficiently and seamlessly. Understanding that they're functionally identical, and that the real choice is about style, will empower you to write cleaner, more maintainable code without second-guessing yourself.