Is there a way to ensure that a single object is bound to a record in the ActiveRecord hierarchy?

It seems that when I take some hierarchical ActiveRecord structure there are multiple hits in the database. I improved this by using the: include option to form the largest possible structure. However, it seems that ActiveRecord does not display the reciprocal sides of the relationship (like parent-child) with unique record references. That is, we get the navigation structure ActiveRecord, but, as far as I know, does not guarantee a unique copy of this 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? Due to shortcomings like this, have other alternative ORMs switched over? (Don't get me wrong: ActiveRecord is a great tool, but all tools have strengths and weaknesses.)

Suppose I were to write my own SQL query (it might even be stored by a proc), returning multiple result sets (one per table) containing all the relevant data for my ActiveRecord hierarchy. Is there a painless way to explicitly map associations if ActiveRecord doesn't accept my explicit mappings to try to create new associations?

+2


source to share


4 answers


I just don't think ActiveRecord is designed to support this idea. It just means that you need to work with ActiveRecord, understanding its pros and cons. Since then, I've found ways to work around this problem.

I looked at DataMapper and I can see that it specifically addresses this issue:



One row in the database must equal one object reference. Quite a simple idea. Quite a deep influence. If you run the following code in ActiveRecord you will see all false results. Do the same in DataMapper and its true all the way down ...

0


source


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



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

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

      

0


source


Sorry, I think you are stuck. This is not something that ActiveRecord supports, and as far as I know there are no plans to support it. As you can see in the question that Sara May is referring to, there are some possible issues.

If you could provide a little more information about your use case, it might help us figure out if there is another way to solve your problem.

0


source


For those who have faced through the years after he was asked (like me!), Go fooobar.com/questions/1289780 / ... .

It is suggested to use it :inverse_of

to set up bidirectional associations. I wish I had filmed this documentation that many times in the past!

0


source







All Articles