Saturday, June 06, 2009

Finding ActiveRecord Associations

Im working away on ActiveJquery, and the next thing on the list, is to add support for relationships. This gets to be really interesting, because your Inside the box, in a plugin, and you need to know what associations the user has
defined.

I was scanning the documentation, and looking around for the api to find the information.

After searching for a while, I discovered railway, a gem for rails that does diagraming of rails models using dot. So grab the gem, and look thru the source.

So the key to finding associations is:

@associations = table.reflect_on_all_associations

This results in:
@associations=
[#ActiveRecord::Reflection::AssociationReflection:0x26305cc
@active_record=
Company(id: integer, name: string, location_id: integer, created_at: datetime, updated_at: datetime),
@macro=:has_many,
@name=:user,
@options={:extend=>[]}>,
#<ActiveRecord::Reflection::AssociationReflection:0x262faa0
@active_record=
Company(id: integer, name: string, location_id: integer, created_at: datetime, updated_at: datetime),
@macro=:has_many,
@name=:location,
@options={:extend=>[]}>,
#<ActiveRecord::Reflection::AssociationReflection:0x262f0c8
@active_record=
Company(id: integer, name: string, location_id: integer, created_at: datetime, updated_at: datetime),
@macro=:has_many,
@name=:division,
@options={:extend=>[]}>],



From my models:
class Company < ActiveRecord::Base
has_many :user
has_many :location
has_many :division

end
class Department < ActiveRecord::Base
belongs_to :division
end
class Division < ActiveRecord::Base
belongs_to :company
end
class Location < ActiveRecord::Base
end
class User < ActiveRecord::Base
end

1 comment:

Steve Schwartz said...

Awesome, I was looking for this! Thanks. Be sure to check out the related methods for inspecting specific associations, etc:

http://api.rubyonrails.org/classes/ActiveRecord/Reflection/ClassMethods.html