Forum: Ruby on Rails Model relationships and clean views

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.
David (Guest)
on 2007-01-19 02:32
I'm new to RoR and am working on the development of a small project
management application just to get my hands wet. Consider the following
model entities:

class Site < ARB
  has_many :projects
end

class Project < ARB
  belongs_to :site
  has_many :tasks
end

class Task < ARB
  belongs_to :project
  belongs_to :user
end

class User < ARB
  has_many :tasks
end

How can I display all sites and their "child" projects without making my
view totally disgusting (or my controller for that matter)? For example:

class site_controller < ApplicationController
  def list
   @sites = Site.find(:all)
  end
end

site/list.rhtml #view
 <% @sites.each do |site|
    projects = site.projects.find(:all) %>
   <%= site.name %>
   <% projects.each do |project| %>
     <%= project.name %>
  <% end %>
 <% end %>

That's obviously not the way to do it. Suggestions?
Mick S. (Guest)
on 2007-01-19 02:55
You need to use partial templates:

site/list.rhtml #view
  <%= render(:partial => "site", :collection => @sites) %>

site/_site.rhtml # partial template to render each site
  <%= site.name %>
  <%= render(:partial => "project", :collection =>
site.projects.find(:all)) %>

site/_project.rhtml # partial template to render each project
  <%= project.name %>

HTH :)
This topic is locked and can not be replied to.