【问题标题】:How to manage multiple roles using polymorphic association in rails?如何在 Rails 中使用多态关联管理多个角色?
【发布时间】:2015-05-28 07:13:06
【问题描述】:

我正在使用 devise 进行身份验证并想办法摆脱这种情况。

我可以探索具有多个角色的同一个设计用户吗?这样他就可以同时作为教师或家长登录?基本上他可以像多个角色一样切换帐户。

class User < ActiveRecord
  belongs_to :loginable, polymorphic: true
end

class Parent < ActiveRecord
  has_one :user, as: :loginable
end

class Teacher < ActiveRecord
  has_one :user, as: :loginable
end


for eg: loginable_type: "Parent", loginable_id: 123

如果用户以“教师”及其 ID 身份登录,我想找到一种方法来更改上述字段。

【问题讨论】:

  • 你到底想做什么
  • 我希望同一用户可以作为“教师”或“家长”登录。这就像转换角色。
  • 您是否正在从管理员端寻找类似“别名登录”的功能?
  • 不完全是,但每个用户......因为一个家长也可以是老师......所以我有不同的家长机制和不同的教师......

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 polymorphic-associations


【解决方案1】:

您可以添加多态has_many 关系:

class CreateUserRoles < ActiveRecord::Migration
  def change
    create_table :user_roles do |t|
      t.integer :role_id
      t.integer :user_id
      t.string  :role_type # stores the class of role
      t.timestamps
    end
    add_index :user_roles, [:role_id, :role_type]
  end
end

class AddActiveRoleToUser < ActiveRecord::Migration
  def change
    change_table :user_roles do |t|
      t.integer :active_role_id
      t.timestamps
    end
  end
end

class User < ActiveRecord
   has_many :roles, polymorphic: true
   has_one :active_role, polymorphic: true


   def has_role? role_name
     self.roles.where(role_type: role_name).any?
   end
end

【讨论】:

  • 所以我必须删除我的可登录多态关联才能使其工作?
  • 感谢 maxcal,您的解决方案提供了很好的解决方案。它给我指明了方向。仍在寻找更好的解决方案。 +1
猜你喜欢
  • 2021-03-23
  • 1970-01-01
  • 1970-01-01
  • 2014-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多