Self Reference, Almost There (I Hope!)

I'm still struggling with the self reference. I *THINK* I'm getting close. I have the following tables:

class CreateCategories < ActiveRecord::Migration   def self.up     create_table :categories do |t|     t.string :name, :limit => 40       t.timestamps     end   end end

class CreateRelationships < ActiveRecord::Migration   def self.up     create_table :relationships, :id => false do |t|     t.integer :category_id     t.integer :parent_id     t.integer :sort_order       t.timestamps     end   end end

My models look like this:

class Relationship < ActiveRecord::Base   belongs_to :category, :class_name => 'Category',        :foreign_key => 'category_id'   belongs_to :parent, :class_name => 'Category',              :foreign_key => 'parent_id end

class Category < ActiveRecord::Base   has_many :relationships, :foreign_key => 'category_id'

  has_many :parents, :class_name => 'Category',                      :through => 'relationships',                      :source => :parent

  has_many :children, :class_name => 'Category',                       :through => 'relationships',                       :source => :category end

I can create a category. When I try to add a parent to it (e.g. c.parents << p) I get the error

ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association "relationships" in model Category

I'm sure that I'm missing something simple, but I don't see it. Can anyone let me know what I'm missing?

Thanks much ---Michael

class CreateRelationships < ActiveRecord::Migration def self.up create_table :relationships, :id => false do |t| t.integer :category_id t.integer :parent_id t.integer :sort_order t.timestamps end end end

If "relationships" is a join table, then it can't have any fields other than the two foreign keys.

class Relationship < ActiveRecord::Base belongs_to :category, :class_name => 'Category', :foreign_key => 'category_id' belongs_to :parent, :class_name => 'Category', :foreign_key => 'parent_id end

Right - so Relationship is an AR model - it *needs* an ID column.

There might be some other issues... but get to them after the Relationship models are working (try creating one in the console to make sure it works...)


Also, you need to refer to the relationships association in the Category class as follows:

has_many :parents, :class_name => 'Category', :through => :relationships, :source => :parent

(In case there's anybody still interested :slight_smile: )