Last active
November 6, 2019 09:09
-
-
Save DonSchado/889a37ee2f352c2ad62a300f473c72ee to your computer and use it in GitHub Desktop.
ActiveRecord Playground File `irb -r ./playground.rb` (or `pry ...`)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'bundler/inline' | |
gemfile do | |
source 'https://rubygems.org' | |
gem 'sqlite3' | |
gem 'activerecord', "~> 6.0.0.rc2" | |
end | |
require 'active_record' | |
ActiveRecord::Base.belongs_to_required_by_default = true | |
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:') | |
ActiveRecord::Schema.define do | |
create_table :posts, force: true do |t| | |
t.string :title | |
t.text :content | |
t.timestamps | |
end | |
create_table :comments, force: true do |t| | |
t.string :name | |
t.text :content | |
t.belongs_to :post, index: true | |
t.timestamps | |
end | |
end | |
class Post < ActiveRecord::Base | |
has_many :comments, dependent: :destroy | |
end | |
class Comment < ActiveRecord::Base | |
belongs_to :post | |
end | |
post = Post.create(title: 'Hello World!', content: "Look at all the things I'm not doing.") | |
3.times do |comment| | |
post.comments.create(name: "User #{comment}", content: "I wrote comment ##{comment}") | |
end | |
=begin | |
[1] pry(main)> Post.count | |
=> 1 | |
[2] pry(main)> Post.first.comments | |
=> [#<Comment:0x00007fec2e379980 id: 1, name: "User 0", content: "I wrote comment #0", post_id: 1, created_at: 2019-01-04 14:28:23 UTC, updated_at: 2019-01-04 14:28:23 UTC>, | |
#<Comment:0x00007fec2e3795e8 id: 2, name: "User 1", content: "I wrote comment #1", post_id: 1, created_at: 2019-01-04 14:28:23 UTC, updated_at: 2019-01-04 14:28:23 UTC>, | |
#<Comment:0x00007fec2e3792c8 id: 3, name: "User 2", content: "I wrote comment #2", post_id: 1, created_at: 2019-01-04 14:28:23 UTC, updated_at: 2019-01-04 14:28:23 UTC>] | |
=end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment