random_record = Model.find(:first, :conditions => ["id < ?", Model.maximum('id')])
There is one deficiency in the preceding code??”if large sections of the database are
deleted, there will be large gaps in the record IDs, so some records are less likely to be selected
than others. If a more perfectly random selection method is important to you, you can solve
this problem by creating a separate index column in your model that can be reindexed every
once in a while, to remove gaps.
CHAPTER 8 ?– ACTIVE RECORD AND THE REAL WORLD 207
How Do IModel X with Active Record?
While each application may have its own data model needs, there are common patterns that
will emerge once you start to use Active Record for your application. Also, if you are familiar
with other ORM libraries, it may be helpful to see how data models with which you may be
familiar are built using Active Record. Some common data models and explanations of how
they would be coded follow in Listings 8-1 to 8-7.
Listing 8-1. Customers and employees
class Company < ActiveRecord::Base
has_many :employees
end
class Employee < ActiveRecord::Base
belongs_to :company
end
Listing 8-2.
Pages:
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475