1

我一直在阅读 Rails 的一些 STI 继承示例,虽然它看起来适合我的需要(从用户的基类继承的用户角色/类型)。似乎它不能很好地处理具有多个角色的用户。特别是因为它依赖于数据库中的类型字段。

有没有快速简便的解决方法?

4

3 回答 3

3

我不确定 STI 是否是用户角色/用户场景中的正确解决方案 - 我不认为用户角色/类型是特定形式的用户。我将有以下架构:

class Membership < ActiveRecord::Base
  belongs_to :user     # foreign key - user_id
  belongs_to :role     # foreign key - role_id
end
class User < ActiveRecord::Base
  has_many :memberships
  has_many :roles, :through => :membership
end
class Role < ActiveRecord::Base
  has_many :memberships
  has_many :users, :through => :membership
end

另一种方法是使用has_and_belongs_to_many. 您可能还想查看restful_authentication插件。

于 2009-08-28T01:43:49.917 回答
1

easy_roles gem 可能是解决您的问题的好方法。你可以在 github 上找到它。正如其他人已经说过的那样,STI 不是你可以实现你的东西的方式。

于 2013-08-02T16:49:15.600 回答
0

就像安迪说的,has_and_belongs_to_many是另一种方式来做到这一点。

# user.rb
class User < ActiveRecord::Base
  has_and_belongs_to_many :roles
end

# role.rb
class Role < ActiveRecord::Base
  has_and_belongs_to_many :users
end

注意:您仍然需要数据库中的关联表,但它只是对您的模型隐藏。

于 2010-11-25T02:45:55.153 回答