Skip to content

Repository files navigation

Simple Record

Introduction

This repository is created for learning purpose. I try to re-implement these basic features of Rails ActiveRecord by myself:

  • Some basic query methods.
  • Basic associations.

Setup

Config your local database type and name into config/database.yml

development:
  adapter: postgresql
  database: hdev

Add your model inside the user_models folder

# user_models/user.rb
class User < SimpleRecord
  has_many :posts
end

# user_models/post.rb
class Post < SimpleRecord
end

Basic query methods

.find

Find a record by primary key. It will return a simple record object.

user = User.find 1

.where

Find a collection of records by condition.

users = User.where(name: ['Huy', 'Harry', 'Phung'])

You can chain .where method as same as Rails ActiveRecord.

users = User.where(name: ['Huy', 'Harry', 'Phung']).where(role: 'Admin')

The .where chain is lazy load. It only hit the Database when use use .evaluate

users = User.where(name: ['Huy', 'Harry', 'Phung']).evaluate

includes

Includes work as same as Rails ActiveRecord includes to reload relationships. .includes is lazy load as same as .where.

users = User.where(name: ['Huy', 'Harry', 'Phung']).includes(:posts).where(role: 'Admin').evaluate

Basic association method

has_many

# Basic case
has_many :post

# Or more options
has_many :post, foreign_key: :owner_id, class_name: BlogPost

About

Rebuild a SimpleRecord base on Rails ActiveRecord

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages