Inspired by Active Record, Objectify is a Ruby object-relational mapping (ORM) library, which uses SQLite3 as its database. Objectify provides an
SQLObject base class. When users define a new class (model) that is a subclass of
SQLObject, a mapping between the model and an existing table in the database is established. Moreover, models can connect with other models by defining associations.
For demo purposes, a database
geo.db is provided. To experience Objectify, run the following commands in your terminal:
git clone https://github.com/davidfeng88/Objectify.git
- Try the following commands!
City.all beijing = City.first canada = Country.last Country.find(3) japan = Country.where(name: "Japan").first kyoto = City.new(name: "kyoto", country_id: japan.id) kyoto.save City.last kyoto.name = "Kyoto" kyoto.save City.last beijing.country canada.continent beijing.continent
Note: Check out
geo.sql file for the content of the demo database.
::allreturns an array of all instances of the class.
::lastreturn first and last instance of the class respectively.
::find(id)returns the instance with the id provided. It returns
nilif not found.
::new(params)creates a new instance with an optional hash of parameters.
#savesaves the changes of the instance in the database. It calls
#updatebased on whether the id is
::columnsreturns an array of column names (symbols).
::table_name=: table name getter and setter methods.
::where(params)takes in a hash of parameters. It returns an empty array if nothing is found. For example:
Country.where(name: "Japan") # => an array of Country instances where the name is "Japan"
- Associations are defined in the
::finalize!. For example:
class Continent < SQLObject has_many :countries finalize! end class Country < SQLObject belongs_to :continent finalize! end
Supported associations currently include
belongs_totakes a required name and an optional hash for
has_one_throughrequires three arguments:
belongs_toassociations. For example, in the demo database:
- I defined a
Cityusing the following options:
Use Objectify with your own database
- Write a SQL source file (
cat FILENAME.sql | sqlite3 FILENAME.dbto generates the database file (
- Edit the
/lib/db_connection.rbso that they point to the
.dbfiles in step 1 and 2.
- Write a Ruby file (
.rb) to define the models and set up the associations.
pry, load the
.rbfile and you are good to go!
whereso that it is lazy and stackable. Implement a
- Validation methods/validator class.
- This should handle both
belongs_to => has_manyand
has_many => belongs_to.
- This should handle both
- Write an
includesmethod that does pre-fetching.