ActiveRecord relationship

hi

i have a question about relationships. if i have the folowing
classes/tables:

project --1--------------n-- iteration

iteration has a attribut “start_date”. now i like to get all projects
whit at least one iteration where start_date = today. for other
calculatings i need all iterations related to this projects.

how can i do this whit activerecord?

thanks for any hints!

From memory something like this:

class Project < ActiveRecord::Base

has_many :iterations do
def todays_it( today )
find :all, :conditions => [ ‘start_date = ?’, today ]
end
end

end

class Iteration < ActiveRecord::Base

belongs_to :project

end

Now you can do the following

all_projects_iterations = Project.find(:all).iterations.todays_it(today)

On Dec 8, 5:53 pm, den [email protected] wrote:

how can i do this whit activerecord?

something like this?

class Iteration < ActiveRecord::Base
belongs_to :project
end

class Project < ActiveRecord::Base
has_many :iterations

def self.find_all_with_iteration_start_date (d)
Iteration.find_all_by_start_date(d).collect { |i| i.project }
end
end

projects = Project.find_all_with_iteration_start_date (today)

class Iteration < ActiveRecord::Base
belongs_to :project
end

class Project < ActiveRecord::Base
has_many :iterations

def self.find_all_with_iteration_start_date (d)
Iteration.find_all_by_start_date(d).collect { |i| i.project }
end
end

projects = Project.find_all_with_iteration_start_date (today)

Could this be refactored:

projects = Iteration.find_all_by_start_date(today).collect { |i|
i.project }

Could this be refactored:

projects = Iteration.find_all_by_start_date(today).collect { |i|
i.project }

I’m not sure it’s a “refactoring” - it’s exactly the same thing. The
original poster seemed to imply that he conceptually wanted the method
to be accessible through the Project model, so that’s why I suggested
the convenience method I did.

-r

thanks for your suggestion.

Peter wrote:

all_projects_iterations = Project.find(:all).iterations.todays_it(today)

this can’t work, because Project.find(:all) returns a array and this
dosn’t know the method iterations.

i’m not sure if this should happens by your code, but i need in the end
a array filed whit Project-objects whit all relatet Iterations - if it
is possible whit no extra query.

know someone a documentation for has_many whit a block given? there is
no word in the rails api about this.

thanks to for all your help. the solution from ryan works great and is
easy to use. now i just have to understand in detail why it works. :wink: