Skip to content

Instantly share code, notes, and snippets.

@MatthewRDodds
Created January 6, 2015 19:10
Show Gist options
  • Save MatthewRDodds/105b7f55db1ba144343d to your computer and use it in GitHub Desktop.
Save MatthewRDodds/105b7f55db1ba144343d to your computer and use it in GitHub Desktop.
Super Simple Active Record Example
require 'active_record'
require 'sqlite3'
ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: ":memory:" )
ActiveRecord::Schema.define(version: 1) do
create_table :articles do |t|
t.string :title
t.date :published_at
t.timestamps
end
create_table :comments do |t|
t.string :content
t.integer :article_id
t.date :published_at
t.timestamps
end
end
class Article < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :article
end
module Commentable
extend ActiveSupport::Concern
included do |base|
has_many :comments, as: :commentable
end
end
Article.delete_all
Comment.delete_all
@article = Article.create(
title: 'My article',
published_at: Date.today
)
Comment.create(
content: 'I liked your article',
published_at: Date.today,
article_id: @article.id)
Comment.create(
content: 'Ditto',
published_at: Date.today,
article_id: @article.id
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment