19

I have two models, TreeNode and User. Each user has_one TreeNode, which is the root of the tree.

class TreeNode
  acts_as_tree
  belongs_to :user
end

class User
  has_one :tree_node
end

I would like to have this setup so that rails will make the association so that I can do something like

User.first.tree

instead of

User.first.tree_node

How would one go about doing something like this?

Bryan Ward
  • 6,443
  • 8
  • 37
  • 48

2 Answers2

30
has_one :tree, :class_name => "TreeNode"

Keep in mind, this assumes a foreign key called user_id in the tree_nodes table.

Edit: If that doesn't work, you might need to specify the foreign key (:foreign_key => :user_id), but I don't think so.

Matt Grande
  • 11,964
  • 6
  • 62
  • 89
3

Apparently :class_name has been replaced with :source.

kbighorse
  • 389
  • 1
  • 2
  • 15
  • 4
    According to [the rails association guide](http://guides.rubyonrails.org/association_basics.html), both :class_name and :source still exist. :source is for specifying the the source association of a `:has_one ... :through` – Eric Hu Oct 12 '11 at 19:10