I have been trying to get ActiveRecord to recognize a parent child relationship between the same object from a link table in my database. Following are the tables.
create_table :parent_account_child_accounts do |t| t.column :parent_account_id, :int t.column :child_account_id, :int end
create_table :accounts do |t| t.column :name, :string ... end
I have an Account ActiveRecord::Base Model. The only way I have been able to map the parent child relationship is thru the associations and a method in my Model. I want to be able to have the built in Association ClassMethods do this for me. So far I have this.
(association in my Account model) has_many :childAccounts, :class_name => "ParentAccountChildAccount", :foreign_key => :parent_account_id has_many :parentAccounts, :class_name => "ParentAccountChildAccount", :foreign_key => :child_account_id
(instance methods in my Account model)
def parent Account.find(self.parentAccounts[0].parent_account_id) end
def children childrenAccounts = self.childAccounts.each do | childAccount | childrenAccounts << Account.find(childAccount.child_account_id) end
childrenAccounts end
But it would be nice to specify something like the following, if this is possible. Thx for everyones help.
has_many :children, :class_name => "Account", :through => "ParentAccountChildAccount", :foreign_key => :parent_account_id
(OK, Just so everyone knows, this is my 2nd day w/ using Ruby/Rails [I am a Java guy], so if I am doing something or many somethings wrong, show me the way!)