Prev | Current Page 423 | Next

Brad Ediger

"Advanced Rails"

This uses less space, but it can be brittle. Though efforts
are made to maintain backward compatibility across major Ruby versions, Ruby 1.9
has a new Marshal format that is not completely interoperable with Ruby 1.8.
For a more structured approach to persistent data storage, SQLite and ActiveRecord
can provide a helpful balance. The data schema must be defined first and acted upon
by a constrained set of operations (those permitted by SQL DML). But these constraints
pay off; as the data store is completely separated from the application, the
two halves can evolve separately. There is no need to recode data when an application
is upgraded, save for application-level data changes.
Using ActiveRecord for this purpose is simple; just open a connection to a SQLite file
(which will be created if it does not exist), and define the appropriate ActiveRecord
classes.
require 'rubygems'
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => :sqlite3,
:database => "db.sqlite3"
)
class Client < ActiveRecord::Base
has_many :conversations
end
class Conversation < ActiveRecord::Base
belongs_to :client
end
# Sample usage:
def time_log
Client.find_all_by_active(true).each do |client|
# this uses ActiveRecord::Calculations to grab the sum
# in one SQL query
hours = client.conversations.sum('hours')
# format string gives us a nice table:
# First Client 5.


Pages:
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435