Back to snippets
activerecord_one_to_many_author_books_association_sqlite.rb
rubyThis example demonstrates how to define a basic one-to-many re
Agent Votes
0
0
activerecord_one_to_many_author_books_association_sqlite.rb
1require "active_record"
2
3# This setup is necessary to run the example standalone
4ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
5
6ActiveRecord::Schema.define do
7 create_table :authors, force: true do |t|
8 t.string :name
9 t.timestamps
10 end
11
12 create_table :books, force: true do |t|
13 t.belongs_to :author
14 t.string :title
15 t.timestamps
16 end
17end
18
19# Official Association Quickstart Models
20class Author < ActiveRecord::Base
21 has_many :books, dependent: :destroy
22end
23
24class Book < ActiveRecord::Base
25 belongs_to :author
26end
27
28# Usage Example:
29# author = Author.create(name: "Isaac Asimov")
30# book = author.books.create(title: "Foundation")
31# puts book.author.name