我的解决方案有效,但是有没有办法只使用对象来比较 jquery 值而不必使用逗号分隔的字符串?
此功能是显示已分配给角色的权限。我有一个带有 id 和名称的角色表,一个带有 id 和名称的权限表,以及一个带有 role_id 和 permission_id 的角色权限表。选择角色时,我想查询已经为该角色分配了哪些权限,并在多选列表框中选择它们。
这是我的模型,role.rb 和 permission.rb:
class Role < ActiveRecord::Base
has_and_belongs_to_many :permissions, :join_table => "roles_permissions"
attr_accessible :description, :name
end
class Permission < ActiveRecord::Base
has_and_belongs_to_many :roles, :join_table => "roles_permissions"
attr_accessible :description, :name
end
我的控制器,roles_permissions_controller.rb:
class RolesPermissionsController < ApplicationController
def index
# get all roles
@roles = Role.all
# get all permissions
@all_permissions = Permission.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @roles }
end
end
def update_permissions
# updates the permissions based on the role selected
role = Role.find(params[:role_id])
puts ' list of perms by role:' << role.name << ' id:' << params[:role_id]
# check for nil, create comma seperated string of id's
if role.permissions.first == nil
@permissions = ""
else
@permissions = role.permissions.map{|a| a.id}.join(',').to_s
end
end
end
这是我的路线.rb:
Stats::Application.routes.draw do
resources :permissions
resources :roles
match "/roles_permissions/" => "roles_permissions#index"
get 'roles_permissions/update_permissions', :as => 'update_permissions'
end
我的观点,roles_permissions/index.html.erb:
<%= collection_select(:role, :id, @roles, :id, :name, options ={:prompt => "-Select a role"}) %>
<br/>
<%= collection_select(:permission, :id, @all_permissions, :id, :name, options ={},html_options ={ :multiple => true, :size => 10}) %>
<br/>
<script>
$(document).ready(
function()
{
$('#role_id').change(
function()
{
$.ajax({
url: "<%= update_permissions_path %>",
data:
{
role_id : $(this).val()
},
dataType: "script"
});
}
);
}
);
</script>
最后是我的 js 文件 update_permissions.js.erb:
var permissions = "<%= @permissions%>";
$('#permission_id').val( permissions.split(",") );