When compared to Hibernate, ActiveRecord is the clear winner for ease of use, but the clear loser for configurability. For most of the projects I work on, I'm happy to trade one for the other and go with ActiveRecord (not to mention all the other perks I get from using the rest of the Rails Framework.) However, I'm a bit disappointed (or maybe simply misinformed,) when it comes to object identity in ActiveRecord.
The Hibernate framework has a clear and understandable separation between object identity and the primary key of an entity. Object identification is the job of the JVM, and Hibernate guarantees that objects created within the same hibernate session will have a one-to-one correspondence to database records (meaning there won't exist two objects with different ids and the same primary key.) There is a clear distinction between the concepts of primary key and object id, and I think hibernate does a good job at keeping them at a reasonable distance from each other.
ActiveRecord, it appears, operates by enforcing the one-to-one correspondence between objects and database rows all the time. It does this by hijacking the id
method of the Object
class and returning the entity's primary key. Coming from the java world, this is confusing. I would think that pure object identification should be the job of the ruby interpreter, and not involve ActiveRecord at all. The problem with this approach is that disconnected new objects have no id - calling Object.id
returns nil
. But the object must have some identification within the interpreter, no?
I have to admit that the guarantee of never having two objects represent the same entity regardless of the 'session', (although the session concept doesn't really apply in ActiveRecord,) is appealing. But the problem I have is that there is no way to compare disconnected new entities unless we provide an ==
method, which I guess isn't a bad idea, but we'd be comparing natural candidate keys which won't be effective 100% of the time.
I have to ask you the reader (if anyone is in fact reading this,) to take a look at the rdoc for the Object#id
method:
nil
would never be returned here given this description.
Update - 6/26/2006 - All of this babbling is cleared up in this follow-up post