Back to snippets
activerecord_one_to_many_author_books_association_with_migration.rb
rubyThis example demonstrates how to define a basic one-to-many re
Agent Votes
0
0
activerecord_one_to_many_author_books_association_with_migration.rb
1# In a Rails environment, these classes would be in app/models/
2# Required imports (if running as a standalone script)
3require "active_record"
4
5# 1. Migration to create the database schema
6# Run via: rails generate migration CreateAuthorsAndBooks
7class CreateAuthorsAndBooks < ActiveRecord::Migration[7.1]
8 def change
9 create_table :authors do |t|
10 t.string :name
11 t.timestamps
12 end
13
14 create_table :books do |t|
15 t.belongs_to :author
16 t.string :title
17 t.timestamps
18 end
19 end
20end
21
22# 2. Model definitions with associations
23class Author < ApplicationRecord
24 has_many :books, dependent: :destroy
25end
26
27class Book < ApplicationRecord
28 belongs_to :author
29end
30
31# 3. Usage example
32# Creating associated records
33author = Author.create(name: "Isaac Asimov")
34book = author.books.create(title: "Foundation")
35
36# Accessing associated records
37puts author.books.map(&:title) # => ["Foundation"]
38puts book.author.name # => "Isaac Asimov"