Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Models
- class Agent < ActiveRecord::Base
- belongs_to :manager
- belongs_to :site
- belongs_to :workgroup
- end
- class Manager < ActiveRecord::Base
- has_many :agents
- 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.all(:conditions => ["agents.workgroup_id=?", @workgroup]) %>
- <h3><%= manager.name %></h3>
- <ul>
- <% for agent in manager.agents.all(:conditions => ["agents.workgroup_id=?", @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
Add Comment
Please, Sign In to add comment