Create, update, and delete Users

Now that we've defined a domain object class, we can write a script that makes use of this.

Create a new user and save it to the database

require 'tutorial_setup'

ten_years_ago = Date.today - (365 * 10)
john = User.new(
  'birthday' => ten_years_ago,
  'email' => 'john.doe@email.com',
  'first_name' => 'John',
  'last_name' => 'Doe',
  'password' => 'my_password'
)
john.commit

To create a user, you instantiate it with a hash. Notice that for the birthday field you don't have to think about SQL date formats; Lafcadio takes care of that automatically for you.

If you run this script you'll find that your users table will have one record in it with an pk_id 1; this is John Doe.

Retrieve a user and change some values

require 'tutorial_setup'

john = User[1]
ten_years = 365 * 10
john.birthday -= ten_years
john.email = 'john.doe@mail.email.com'
john.commit

Note that all the domain object properties can be accessed like any object's properties. Furthermore, when you committed the object last time, the object store inserted a row into the database. This time, it updates the pre-existing row instead.

Delete the user

require 'tutorial_setup'

john = User[1]
john.delete = true
john.commit