The Difference between build and new in Ruby on Rails & ActiveRecord

The Difference between build and new in Ruby on Rails & ActiveRecord

TLDR: For an ActiveRecord Association new and build are the same.

Let’s take a look at a simple user/organization relationship to see how new and build work for assocations.

First we create, the following migration:

class UserOrganizationTables < ActiveRecord::Migration
  def change
    create_table :users, force: :cascade do |t|
      t.string   :email, null: false
      t.string   :crypted_password
      t.string   :salt
      t.string   :first_name
      t.string   :last_name
      t.timestamps
    end

    create_table :organizations, force: :cascade do |t|
      t.string   :name, null: false
      t.timestamps
    end

    create_table :user_organizations, force: :cascade do |t|
      t.belongs_to :user
      t.belongs_to :organization
      t.timestamps
    end
  end
end

With the following relations:

class Organization < ActiveRecord::Base
  has_many :user_organizations
  has_many :users, through: :user_organizations
end

class UserOrganization < ActiveRecord::Base
  belongs_to :user
  belongs_to :organization
end

class User < ActiveRecord::Base
  has_many :user_organizations
  has_many :organizations, through: :user_organizations
end

Now to create a user within this organization, we can use the users relation an organization object:

def create
  @organization = Organization.find(params[:organization_id])
  @user = @organization.users.new(user_params)
  if @organization.save
    redirect_to [@organization, :index]
  else
    render :new, status: :unprocessable_entity
  end
end

def user_params
  params.require(:user).permit(:email, :password, :password_confirmation))
end

The important thing to notice here is that we use organization.save and not user.save.