Chapter 5. Using domain classes

Table of Contents

Inserting, updating, and deleting
Dynamic associations
Triggers

Inserting, updating, and deleting

To insert a table row with Lafcadio, simply create a domain object in Ruby, then commit it. A newly created domain object has no pk_id set, but this will be set once it's been committed.

user = User.new( 'first_name' => 'John', 'last_name' => 'Doe' )
puts user.pk_id     # nil
user.commit
puts user.pk_id     # won't be nil

Unless you're writing test code and using the MockObjectStore, it's not recommended to create a domain object with a pk_id. Doing so will override the database's role in setting the primary key for you, and can have unpredictable results.

# Don't do this:
user = User.new( 'pk_id' => 99, 'first_name' => 'John', 'last_name' => 'Doe' )
user.commit

To update an existing domain object, you retrieve it with DomainObject[], modify some fields, and then commit it.

user = User[5555]
user.last_name = 'Smith'
user.commit

You can shortcut this with DomainObject#update!, with takes a hash of values to update, and then commits the domain object.

user.update!( 'last_name' => 'Smith' )

Deleting a domain object simply involves setting DomainObject.delete to true, and then committing it.

user.delete = true
user.commit