Michael Anhari

Creating related records with ActiveRecord

A chain link

Let's say we have a User model and an Article model, and a user has_many articles.

class User < ApplicationRecord
  has_many :articles
end

class Article < ApplicationRecord
  belongs_to :user
end

If we have the @current_user in our controller, we can create articles for that user like so:

Article.create(
  title: "101 Tips",
  description: "All kinds of tips",
  user_id: @current_user.id
)

This will work just fine, but ActiveRecord provides some conveniences because this is such a common task.

Chaining off of the parent object

We could also set this foregin key (user_id) by using create on the has_many relationship. That would look something like this:

@current_user.articles.create(
  title: "101 Tips",
  description: "All kinds of tips"
)

Since we're chaining of the of the has_many/belongs_to relationship, Rails knows how to set this foreign key for us. I like to use this method to make sure I'm always setting the foreign keys as I would expect.

Newsletter

I'm working on sending out a weekly newsletter. I'll make it as easy as possible to unsubscribe at any time.