views:

34

answers:

3

It seems when I grab some hierarchical ActiveRecord structure that there are quite a few hits to the database. I improved this using the :include option to flesh out as much of the structure as possible. Even so, it seems that ActiveRecord does not map the reciprocal sides of a relationship (e.g. parent-child) with unique references to a record. That is, we get a navigable ActiveRecord structure, but one that to my knowledge doesn't guarantee a unique copy of a given record.

node = Node.find(1, :include => {:document => :node})
node.object_id #A
node.document.node.object_id #B although I expect/desire A

Unavoidable in ActiveRecord? Have others moved to alternative ORMs because of shortcomings like this? (Don't get me wrong: ActiveRecord is a great tool. But all tools have strengths and weaknesses.)

Say I were to write my own SQL query (it could even be a stored proc) returning multiple result sets (one per table) containing all the relevant data for my ActiveRecord hierarchy. Is there a painless way that I can explicitly map the associations without having ActiveRecord mistaking my explicit mappings for an attempt to create new associations?

A: 

So, If you have a node, it has a parent_id. For all nodes, the parent must not be the parent of any other node. In other words, for all nodes the parent_id should be unique.

class Node
  has_one :child, :class_name => "Node", :foreign_key => :parent_id

  belongs_to :parent, :class_name => "Node"
  validates_uniqueness_of :parent_id
end
Ariejan
A: 

Unfortunately, I think you're stuck. This is not something supported by ActiveRecord and as far as I know there are no plans to support it. As you can see in the question referenced by Sarah Mei there are some possible concerns with it.

If you could provide a little more information about your use case it might help us to figure out if there's another way to deal with your issue.

Peter Wagenet
This is what I suspected. I guess it has more to do with the ActiveRecord design pattern itself. I can work around it; I just have to be mindful of this potential snafu.
Mario
A: 

I simply don't think ActiveRecord is designed to support this idea. It simply means you have to work with ActiveRecord, understanding its pros and cons. I've since found ways to work around this issue.

I've looked at DataMapper and I see that it does specifially address this issue:

One row in the database should equal one object reference. Pretty simple idea. Pretty profound impact. If you run the following code in ActiveRecord you’ll see all false results. Do the same in DataMapper and it’s true all the way down...

Mario