好的,我有以下设置,需要一些方向。我在这个问题上浪费了将近2天的时间,我需要继续前进:
因此,角色和权限通过RolePermissions关联 角色 - > RolePermission - >许可
我希望创建一个复选框网格,允许我同时编辑所有角色和权限。
这就是我在视觉上寻找的东西:
任何帮助将不胜感激!另外,我使用的是simple_form和bootstrap。
答案 0 :(得分: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-checkboxes和http://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 %>
答案 1 :(得分:1)
将此作为OP的请求作为答案添加:
在habtm上有一个带有复选框的railscast,你可以根据自己的需要调整它:railscasts.com/episodes/17-habtm-checkboxes