动态选择列表框中的多个值

时间:2013-01-04 17:07:50

标签: ruby ruby-on-rails-3 jquery

我的解决方案有效,但有没有办法只使用对象来比较jquery值而不必使用逗号分隔的字符串?

此功能用于显示已分配的角色权限。我有一个带有id和name的角色表,一个带有id和name的权限表,以及一个带有role_id和permission_id的roles_permissions表。选择角色时,我想查询哪些权限已分配给该角色,并在多选列表框中选择它们。

以下是我的模型,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

这是我的routes.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(",") );

0 个答案:

没有答案