Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of using active record without Rails
# Run `gem install active_record sqlite3` to install the dependencies
ENV['DATABASE_URL'] = 'sqlite3:/tmp/sqlite.test' # Change this to anything you want
require 'sqlite3' # Make sure to require the correct adapter for your `DATABASE_URL`
require 'active_record'
ActiveRecord::Base.establish_connection
ActiveRecord::Schema.define do
create_table :users do |t|
t.column :name, :string
t.timestamps
end
create_table :posts do |t|
t.column :user_id, :integer
t.column :title, :string
t.column :body, :text
t.timestamps
end
end
class User < ActiveRecord::Base
has_many :post
end
class Post < ActiveRecord::Base
belongs_to :user
end
# Example codes
User.count # => 0 (we don't have any record in table `users` yet)
user = User.create(name: "John")
User.count # => 1 (now we have one user, which is John)
user.destroy
User.count # => 0
# If you know that the table exists and you just want to quickly connect to it:
class User < ActiveRecord::Base
establish_connection "sqlite3:/tmp/sqlite.test" # Change this to your database url
end
User.count # => 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment