Skip to content

Instantly share code, notes, and snippets.

@drd
Forked from tamalw/gist:11302
Created September 17, 2008 21:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drd/11313 to your computer and use it in GitHub Desktop.
Save drd/11313 to your computer and use it in GitHub Desktop.
# Models
class Agent < ActiveRecord::Base
belongs_to :manager
belongs_to :site
belongs_to :workgroup
named_scope :of_workgroup, lambda { |workgroup| {:conditions => ['workgroup_id = ?', @workgroup.id] }
end
class Manager < ActiveRecord::Base
has_many :agents
named_scope :of_workgroup, lambda { |workgroup| {:conditions => ['workgroup_id = ?', @workgroup.id] }
end
class Site < ActiveRecord::Base
has_many :agents
has_many :managers, :through => :agents, :uniq => true, :order => "managers.name"
has_many :workgroups, :through => :agents, :uniq => true, :order => "workgroups.name"
end
class Workgroup < ActiveRecord::Base
has_many :agents
has_many :managers, :through => :agents, :uniq => true, :order => "managers.name"
has_many :sites, :through => :agents, :uniq => true, :order => "sites.name"
end
# Controller
class WorkgroupsController < ApplicationController
def show
@workgroup = Workgroup.find(params[:id])
end
end
# Existing view
<% for site in @workgroup.sites %>
<h2><em><%= site.name %></em></h2>
<% for manager in site.managers %>
<h3><%= manager.name %></h3>
<ul>
<% for agent in manager.agents %>
<li><%= link_to agent.name, agent_path(agent.id) %></li>
<% end %>
</ul>
<% end %>
<% end %>
# It's a scoping problem, but I just can't put my finger on it right now.
# Because workgroups can have more than one site, and sites can have more than one workgroup
# not to mention that managers can have agents that span workgroups, this hierarchy breaks down.
# I don't think that I want to lock it in a certain way in the associations because I need the flexibility
# later to look at a group of agents by site, manager, or workgroup independently.
# New view
<% for site in @workgroup.sites %>
<h2><em><%= site.name %></em></h2>
<% for manager in site.managers.of_workgroup(@workgroup) %>
<h3><%= manager.name %></h3>
<ul>
<% for agent in manager.agents.of_workgroup(@workgroup) %>
<li><%= link_to agent.name, agent_path(agent.id) %></li>
<% end %>
</ul>
<% end %>
<% end %>
# Looks ugly. Is there a proper way to do this?
# Ultimately it should look like this:
# Workgroup
# Site A
# Manager 1
# Agent
# Agent
# Agent
# Manager 2
# Agent
# Agent
# Agent
# Site B
# Manager 3
# Agent
# Agent
# Agent
# Manager 4
# Agent
# Agent
# Agent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment