public
Last active — forked from tamalw/gist:11302

  • Download Gist
gistfile1.rbx
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
# 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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.