DEV Community

Cover image for Active Record Associations (one-to-many)
YarixaR
YarixaR

Posted on

Active Record Associations (one-to-many)

It's insane to think that I've already finished my 3rd phase of Bootcamp. Time is flying! In this phase, we finally ventured to the back end of software engineering where we learned a bit about ruby on rails and what happens "under the hood".
For this blog, I've decided to briefly go over associations.

Why Associations?

Declaring associations is a convenient way of connecting two Active Record models. This makes manipulating your data models in logical way.

If you have 2 separate models, you can bring them together by using a foreign key in the migration folder.
Here, we're keeping the user's foreign key stored in the candle's table. Since a candle belongs to a user, it should have a "user_id" to identify which user it belongs to.

ActiveRecord::Schema.define(version: 2022_08_15_211950) do

  create_table "users", force: :cascade do |t|
    t.string "name"
  end

  create_table "candles", force: :cascade do |t|
    t.string "scent"
    t.string "brand"
    t.integer "user_id"
  end

end

Enter fullscreen mode Exit fullscreen mode

But in order for this to work, inside of active records, you need a special macro that ties them together and develops a relationship. This is called a one-to-many.

What is a macro?

A macro is a method that writes code for us. If you're familiar with macros like attr_reader and attr_accessor, Active Record comes with a few handy macros that create new instance methods we can use with our classes.

  • In the users model, we should think that a user has_many candles. The name "candles" has to be pluralized because a single user can have many candles.
  • In the candles model, candles belong_to a user. You'll notice that "user" is written as singular because candles on belong to one user.
# has_many

# app/models/user.rb
class User < ActiveRecord::Base
  has_many :candles

  # naming is plural
  # indicates a one-to-many association
  # a user can have many candles in this example
  # candles associated via `user_id`
end

Enter fullscreen mode Exit fullscreen mode
# belongs_to

# app/models/candle.rb
class Candle < ActiveRecord::Base
  belongs_to :user

  # must be singular
  # Sets up a 1:1 connection with another model - User in this case
  # Books associated to a user via `user_id` on candles table
end
Enter fullscreen mode Exit fullscreen mode

Only after you ran rake db:migrate and planted your seeds, you can go ahead and run rake console to check if they're all properly connected.

Drake meme

Sources:

Top comments (0)