Rails滚动gem / assosiation问题

时间:2016-06-17 09:32:38

标签: ruby-on-rails ruby devise rolify

我使用rolify gem和select * from security.requestview r -- either below two joins satisfy left join security.RequestDelegateView rd on r.id = rd.RequestId join (select top 1 PersonnelNumber from SECURITY.MyRolesView) m on (m.PersonnelNumber=r.RequestorId or m.PersonnelNumber=r.InitiatorId or m.PersonnelNumber=rd.DelegatePersonnelNumber) -- or this join join (select substring(ltrim(DDSUCode),0,3) as Division from security.staffview where PersonnelNumber = (select top 1 PersonnelNumber from SECURITY.MyRolesView)) s on r.OrganizationUnitRefId like s.Division+'%'

的设计

我的AdminUser

Roles

模特'角色'

 class RolifyCreateRoles < ActiveRecord::Migration
  def change
    create_table(:roles) do |t|
      t.string :name
      t.references :resource, :polymorphic => true

      t.timestamps
    end

    create_table(:admin_users_roles, :id => false) do |t|
      t.references :admin_user
      t.references :role
    end

    add_index(:roles, :name)
    add_index(:roles, [ :name, :resource_type, :resource_id ])
    add_index(:admin_users_roles, [ :admin_user_id, :role_id ])
  end
end

我的问题是,当我想让用户属于角色时,它会给出空数组而不是我的adminuser对象

 class Role < ActiveRecord::Base
  has_and_belongs_to_many :admin_users, :join_table => :admin_users_roles

  belongs_to :resource,
             :polymorphic => true

  validates :resource_type,
            :inclusion => { :in => Rolify.resource_types },
            :allow_nil => true

  scopify
end

u = AdminUser.first u.add_role(:admin) &GT;

当我做的时候

u.roles => #<Role id: 1, name: "admin", admin_user_id: 1, resource_id: nil, resource_type: nil, created_at: "2016-06-16 15:03:33", updated_at: "2016-06-17 09:04:30"

2 个答案:

答案 0 :(得分:0)

检查用户是否具有全局角色:

user = User.find(1)
user.add_role :admin # sets a global role
user.has_role? :admin
=> true

或者在实例级别检查您的情况

u = AdminUser.first
u.add_role(:admin)

> Role.first=> #<Role id: 1, name: "admin", admin_user_id: 1,
> resource_id: nil, resource_type: nil, created_at: "2016-06-16
> 15:03:33", updated_at: "2016-06-17 09:29:32">

而不是这样做=&gt; Role.first.admin_users =&gt; [] 尝试

u = AdminUser.first
u.roles

Rolify有一个非常清晰的文档 Rolify

答案 1 :(得分:0)

哦,我通过改变admin_user模型

中的关系来修复它

has_manyhas_and_belongs_to_many :roles