Last active
May 25, 2022 13:52
-
-
Save wzulfikar/1580f9e08ecccc3e1dc51c2456b1c65b to your computer and use it in GitHub Desktop.
Example of using active record without Rails
This file contains hidden or 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
# 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