HABTM association with own class?

If I have a class, Asset, which has and belongs to many associated Asset
objects, how do I do this?

has_and_belongs_to_many :associated_assets, :class => “Asset”,
:foreign_key => ???, :association_foreign_key => ???

Right now, my table has a :first_asset_id and a :second_asset_id, but I
don’t see how the objects themselves are supposed to distinguish one
from the other.

Surely someone here has done this?

Nevermind, I guess a join model is the only way to go.

Dave, with a web site with that name I am sure Josh knows a lot more
about this than I do, but in the case you describe it looks like you
just want a simple self-join. In which case I think what you want is:

def Asset < ActiveRecord::Base
has_and_belongs_to_many :related_assets,
:class_name => “Article”,
:join_table => “related_assets”,
:association_foreign_key => “related_asset_id”,
:foreign_key => “asset_id”
end

And then a table called related_assets with the columns
related_asset_id
and asset_id

Cheers, --Kip

On Sep 7, 6:43 am, Josh S. [email protected]

Dave S. wrote:

If I have a class, Asset, which has and belongs to many associated Asset
objects, how do I do this?

has_and_belongs_to_many :associated_assets, :class => “Asset”,
:foreign_key => ???, :association_foreign_key => ???

Right now, my table has a :first_asset_id and a :second_asset_id, but I
don’t see how the objects themselves are supposed to distinguish one
from the other.

You should be able to do this by using TWO associations and specifying a
slew of options. You need to override pretty much all the basic
defaults. Create a join table called ‘assets_assets’ for the below
example.

Asset:
has_and_belongs_to_many :first_assets, :class_name => “Asset”,
:join_table => “assets_assets”, :foreign_key => “second_asset_id”,
:association_foreign_key => “first_asset_id”
has_and_belongs_to_many :second_assets, :class_name => “Asset”,
:join_table => “assets_assets”, :foreign_key => “first_asset_id”,
:association_foreign_key => “second_asset_id”

Change those association names as you want. Note, this is written in the
email so it’s untested. It’s straightforward though so I’d expect it to
work.


Josh S.
http://blog.hasmanythrough.com