gpt4 book ai didi

ruby-on-rails - 如何使用 has_many :through association 创建复选框网格

转载 作者:行者123 更新时间:2023-12-04 05:07:26 26 4
gpt4 key购买 nike

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

所以 Roles 和 Permissions 是通过 RolePermissions 关联起来的
角色 -> 角色权限 -> 权限

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

这就是我在视觉上寻找的:Roles / Permissions checkbox grid

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

最佳答案

试试这个,

# /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

编辑:

刚注意到我把 table 倒退了。这将把角色放在顶部,将权限放在一边,
# /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 %>

关于ruby-on-rails - 如何使用 has_many :through association 创建复选框网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15345310/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com