2

好的,所以我有以下设置,需要一些指导。我在这个问题上浪费了将近 2 天,我需要继续:

所以 Roles 和 Permissions 是通过 RolePermissions Role -> RolePermission -> Permission 关联的

我希望创建一个复选框网格,允许我同时编辑所有角色和权限。

这就是我在视觉上寻找的东西:角色/权限复选框网格

任何帮助将不胜感激!另外,我正在使用 simple_form 和 bootstrap。

4

2 回答 2

2

试试这个,

# /config/routes.rb

resources :roles do
  collection do
    get :edit_multiple
    put :update_multiple
  end
end


# /app/controllers/roles_controller.rb

class RolesController < ApplicationController
  def edit_multiple
    @roles = Role.all
    @permissions = Permission.all
  end

  def update_multiple
    params[:roles] = {} unless params.has_key?(:roles) # if all checkboxes unchecked.
    Role.all.each do |role|
      # this allows for 0 permission checkboxes being checked for a role.
      unless params[:roles].has_key?(role.id.to_s)
        params[:roles][role.id] = { permission_ids: [] }
      end
    end
    @roles = Role.update(params[:roles].keys, params[:roles].values)
    @roles.reject! { |r| r.errors.empty? }
    if @roles.empty?
      redirect_to edit_multiple_roles_path
    else
      render :edit_multiple
    end
  end
end


# /app/views/roles/edit_multiple.html.erb

<%= form_tag update_multiple_roles_path, method: :put do %>
  <table>
    <tr>
      <th></th>
      <% @permissions.each do |permission| %>
        <th><%= permission.name %></th>
      <% end %>
    </tr>
    <% @roles.each do |role| %>
      <tr>
        <th><%= role.name %></th>
        <% @permissions.each do |permission| %>
          <td><%= check_box_tag "roles[#{role.id}][permission_ids][]", permission.id, role.permissions.include?(permission) %></td>
        <% end %>
      </tr>
    <% end %>
  </table>

  <%= submit_tag "Save" %>
<% end %>


# /app/models/role.rb

class Role < ActiveRecord::Base
  has_many :role_permissions
  has_many :permissions, through: :role_permissions
  attr_accessible :name, :permission_ids
end

它是http://railscasts.com/episodes/17-habtm-checkboxeshttp://railscasts.com/episodes/165-edit-multiple-revised的组合

编辑:

只是注意到我让桌子向后。这会将角色放在顶部,将权限放在一边,

# /app/views/roles/edit_multiple.html.erb

<%= form_tag update_multiple_roles_path, method: :put do %>
  <table>
    <tr>
      <th></th>
      <% @roles.each do |role| %>
        <th><%= role.name %></th>
      <% end %>
    </tr>
    <% @permissions.each do |permission| %>
      <tr>
        <th><%= permission.name %></th>
        <% @roles.each do |role| %>
          <td><%= check_box_tag "roles[#{role.id}][permission_ids][]", permission.id, role.permissions.include?(permission) %></td>
        <% end %>
      </tr>
    <% end %>
  </table>

  <%= submit_tag "Save" %>
<% end %>
于 2013-03-11T18:42:52.470 回答
1

将此作为来自 OP 的请求作为答案添加:

habtm 上有一个带有复选框的 railscast,您可以根据需要对其进行调整:railscasts.com/episodes/17-habtm-checkboxes

于 2013-03-12T09:51:36.710 回答