收集有条件的哈希

时间:2013-03-20 09:19:39

标签: ruby ruby-on-rails-3 ruby-on-rails-3.2

型号:project.rb

def groups_by_role
    member_principals.find(:all, :include => [:principal, :roles]).inject({}) do |h, m|
      m.roles.each do |r|
        h[r] ||= []
        h[r] << m.principal
      end
      h
    end
  end

Controller:projects_controller.rb

@groups_by_role = @project.groups_by_role

观看次数:members_index.html.rb

<% if @groups_by_role.any? %>
<div class="members box">
    <h3><%= l(:label_member_plural)%></h3>
    <p>
        <% @groups_by_role.keys.sort.each do |role| %>
        <%= h role %>: <%= @groups_by_role[role].sort.collect{|u| u}.join(", ").html_safe %>
        <br />
        <% end %>
    </p>
</div>
<% end %>

我有一个模型,它有一个方法group_by_role,可以找到所有的角色和主体。这里,principal定义了属于特定角色的用户和组。此方法是project.rb。

的一部分

后来,我在控制器中为项目定义了相同的方法,并将其分配给实例变量,以供视图使用,即@groups_by_role。

最后,收集并显示特定用户和组的角色。

控制台对特定@project的输出如下所示:@groups_by_role

{#<Role id: 18, name: "Project Manager", permissions: [:add_project, :edit_project, :close_project], issues_visibility: "all">=>[#<User id: 11, login: "test1", firstname: "Test", lastname: "T", type: "User">], 

#<Role id: 26, name: "Readers", permissions: [:view_documents, :view_files], issues_visibility: "default">=>[#<Group id: 835, login: "", firstname: "", lastname: "AA", type: "Group">, #<User id: 107, login: "testab", firstname: "Tommy", lastname: "Ab", type: "User">, #<User id: 111, login: "testxyz", hashed_password: "", firstname: "test", lastname: "xyz", type: "User">]}

@ groups_by_role.class = Hash

问题:现在我将获得带有角色的输出以及相应的用户或组。但我想在这里更改显示。如果哈希只包含没有任何组的用户,那么我只显示用户。因此对于此输出{#<Role id: 18, name: "Project Manager", permissions: [:add_project, :edit_project, :close_project], issues_visibility: "all">=>[#<User id: 11, login: "test1", firstname: "Test", lastname: "T", type: "User">], 因为它只有用户,所以我显示用户。这很好,因为它只有用户而不是组......

但如果哈希中同时存在用户和组,那么我只显示组名而不显示用户。目前它显示的用户和组如下例所示:#<Role id: 26, name: "Readers", permissions: [:view_documents, :view_files], issues_visibility: "default">=>[#<Group id: 835, login: "", firstname: "", lastname: "AA", *type: "Group"*>, #<User id: 107, login: "testab", firstname: "Tommy", lastname: "Ab", *type: "User"*>, #<User id: 111, login: "testxyz", hashed_password: "", firstname: "test", lastname: "xyz", type: "User">]}

是否有任何方法可以在视图或控制器中传递条件,并检查哈希是否同时返回用户和组,然后只显示该组。 有人可以帮助我。任何帮助将非常感激。

1 个答案:

答案 0 :(得分:2)

我希望我能正确理解你。

创建一个辅助方法(用于控制器),它将返回一个如下字符串:

def print_principals(principals)
  if principals.index {|p| p.is_a? Group }
    principals = principals.reject{|u| u.is_a? User }
  end
  # WARNING!!! You should apply html_safe only if you're sure that it 
  # is actually safe, i.e. not input by user. Otherwise consider escaping it.
  principals.sort.collect{|u| u}.join(", ").html_safe 
end

在您看来: <%= h role %>: <%= print_principals @groups_by_role[role] %>