0

In my rails app I have a table called Permissions which has the following columns:

id
name
controller
action
description

I also have a Role, which has an association with each of these Permissions.

When editing a Role, I want to be able to select which of the Permissions are allowed for that Role in the form of checkboxes. However I want to group each of the Permissions by whatever the controller name is.

This is what I have in my view:

<table>
  <% for permission in Permission.all %>
    <tr>
      <th rowspan="2"><%= permission.controller %></th>
      <% for permission in Permission.all %>
      <th style="text-align: center;"><%= permission.action %></th>
      <% end %>
    </tr>
    <tr>
      <% for permission in Permission.all %>
        <td style="text-align: center;"><%= check_box_tag "role[permission_ids][]", permission.id, @role.permissions.include?(permission) %></td>
      <% end %>
    </tr>
  <% end %>
</table>

So as you can see I basically loop through all of the Permissions to create a table row that contains the controller name and all of the actions. I then create another row with all of the checkboxes for each of those actions.

What I want to do is make it so that my loop is for each Permission controller and then right out the permissions that have the same controller.

1 Answer 1

3

First off, I'd advise to avoid querying in the views, you should be setting up some instance variables in the controllers.

Now, regarding to your actual question, what about doing something like the following in your controller:

@permissions_by_controller = Permission.all.group_by(&:controller)

And the in the view you iterate like this:

@permission_by_controller.each do |controller, permissions|
  # here permissions contains every permission for controller
  permissions.each do |permission|
    # here you will have each permission
  end
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.