Accessing children of children using has_many?


#1

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


#2

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 B. http://agileconsultingllc.com
removed_email_address@domain.invalid