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.
Config your local database type and name into config/database.yml
development:
adapter: postgresql
database: hdevAdd 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
endFind a record by primary key. It will return a simple record object.
user = User.find 1Find 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']).evaluateIncludes 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 case
has_many :post
# Or more options
has_many :post, foreign_key: :owner_id, class_name: BlogPost