Forum: Ruby on Rails Accessing children of children using has_many?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
0bc521d302be12bbebd1c955c1f83a01?d=identicon&s=25 Astorian (Guest)
on 2007-07-24 00:20
(Received via mailing list)
Hello. Thanks in advance for your help. What is the slickest way of
accessing children of children.

My understanding is that you can use "Parent.children" to get the
children of an object, but Parent.children.children wont work (while
Child.children will, but doesn't help)

Right now I'm using something like this
--------------
class Challenge < ActiveRecord::Base

has_many  :challengers, :dependent => :destroy
has_many  :posts, :finder_sql => 'SELECT p.* FROM posts p LEFT JOIN
challengers chr ON p.challenger_id=chr.id WHERE chr.challenge_id =
#{id}'
....
--------------

to get from Challenges, through Challengers, to Posts, so I can write
Challenger.posts, but now I am running into trouble while trying to
extend the association.

Any thoughts? Sorry if this is an ignorant question. I'm very new to
this.

John
Ef3aa7f7e577ea8cd620462724ddf73b?d=identicon&s=25 Rob Biedenharn (Guest)
on 2007-07-24 03:58
(Received via mailing list)
On Jul 23, 2007, at 6:17 PM, Astorian wrote:
>
>
> Any thoughts? Sorry if this is an ignorant question. I'm very new to
> this.
>
> John

Here's where the language conventions of Rails (ActiveRecord) really
shine.  Re-read your explanation and then this possible solution:

class Challenge < ActiveRecord::Base
   has_many :challengers, :dependent => :destroy
   has_many :posts, :through => :challengers
end

This assumes that:
class Challenger < ActiveRecord::Base
   belongs_to :challenge
   has_many :posts
end

class Post < ActiveRecord::Base
   belongs_to :challenger
end

-Rob

Rob Biedenharn    http://agileconsultingllc.com
Rob@AgileConsultingLLC.com
This topic is locked and can not be replied to.