1

我有两门红宝石课:-

   class Role < ActiveRecord::Base
       # attr_accessible :title, :body
       acts_as_authorization_role :subject_class_name => 'User', :join_table_name =>   "roles_users"
    end

     class User < ActiveRecord::Base
      acts_as_authentic
          acts_as_authorization_object :role_class_name => 'Role', :subject_class_name => 'User'
          acts_as_authorization_subject :association_name => :roles , :join_table_name => 'roles_users'
          has_one:employee_detail ,:foreign_key => "User_id"

     end

和迁移文件是: -

 class CreateUsers < ActiveRecord::Migration
    def change
    create_table :users do |t|
     t.string :username
     t.string :email
     t.string :crypted_password
     t.string :password_salt
     t.string :persistence_token
     t.timestamps
   end
 end
end


 class CreateRoles < ActiveRecord::Migration
   def change
    create_table "roles" , :force => true  do |t|
      t.string  :name ,             :limit => 40
      t.string  :authorizable_type, :limit => 40
      t.integer :authorizable_id
      t.timestamps
   end
 end
end


 class RolesUsers < ActiveRecord::Migration
   def change
    create_table "roles_users", :id => false, :force => true do |t|
    t.references  :user
    t.references  :role
  end
 end
end

我有用户 ID 并想检索角色 ID,但无法查询中间表。任何人都可以为此提供一些解决方案。谢谢

4

1 回答 1

0

很明显,您的用户将拥有多个角色

您可以在用户中为角色定义一个 habtm 关系并获取检索角色角色,如下所示

class User < ActiveRecord::Base
      acts_as_authentic
      acts_as_authorization_object :role_class_name => 'Role', :subject_class_name => 'User'
      acts_as_authorization_subject :association_name => :roles , :join_table_name => 'roles_users'
      has_one:employee_detail ,:foreign_key => "User_id"
      has_and_belongs_to_many :roles
end

并检索用户的角色,如下所示

user = User.find user_id
user.roles # this will give you roles array
role_ids = user.roles.map { |r| r.id } # if you only want array of ids
于 2012-09-01T11:51:44.620 回答