Active Resource Associations

19 views
Skip to first unread message

Gaston Ramos

unread,
Sep 27, 2010, 3:35:32 PM9/27/10
to rubyonra...@googlegroups.com
Hi all,

I had the idea of add associations to Active Resource, something like AR
associations, but only the 3 basics, belongs_to, has_one and has_many:

class Project < ActiveResource::Base
belongs_to :portfolio
has_one :project_manager
has_many :milestones

end


#--------------------------------------------------------------------
# belogns_to

p = Proyect.new

- p.portfolio
- p.portfolio=(p)

#--------------------------------------------------------------------
# has_one

p = Proyect.new

- p.project_manager
- p.project_manager=(pm)
- p.build_p.project_manager(attributes={})
- p.create_project_manager(attributes={})


#--------------------------------------------------------------------
# has_many

Project#milestones.empty?, Project#milestones.size, Project#milestones,
Project#milestones<<(milestone), Project#milestones.delete(milestone),
Project#milestones.find(milestone_id), Project#milestones.find(:all, options),
Project#milestones.build, Project#milestones.create

The way to create those new association methods could be adding a private
instance variable related to the resource, and add an instance method by
metaprogramming making the method name based on the resource name, so:

IMO this basic 3 associacionts is a good start, i did something like that in
a project that I'm working and works fine, this feature will avoid reptition
of creates all methods by hand like this:

def project_manager
ProjectManager.find(find(:params => { :project_id => id })
end

for every model that you need to "associate".

Regards.


--
"Premature optimization is the root of all evil (or at least most of it) in
programming."

(Donald Knuth)


+-------------------------------------+
Gastón Ramos
http://gastonramos.com.ar/
GNU/Linux Counter user #450312

Reply all
Reply to author
Forward
0 new messages