我在ruby中有两个课程: -
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,但无法查询中间表。谁能为此提供一些解决方案。 thnks
答案 0 :(得分: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