每个用户多个角色的 Rails STI 风格继承

发布于 2024-08-03 08:47:53 字数 125 浏览 6 评论 0原文

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

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

I've been reading up on a bit of STI Inheritence examples for Rails,
While it looks like it would suit my needs (User role/types inheriting from a base class of user). It seems like it doesn't handle a user having multiple roles too well. Particularly because it relies on a type field in the database.

Is there a quick and easy work around to this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

万劫不复 2024-08-10 08:47:53

我不确定 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 插件。

I'm not sure if STI is the right solution in a user role/user scenario - I don't think of User roles/types as a specific form of user. I would have the following schema:

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

Another way of doing this would be to use has_and_belongs_to_many. You might also want to check out the restful_authentication plugin.

寂寞清仓 2024-08-10 08:47:53

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

A good workaround for your problem could be the easy_roles gem. You can find it on github.
As the others already said STI is not the way you can implement your stuff.

没企图 2024-08-10 08:47:53

就像 Andy 所说,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

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

Just like Andy said, has_and_belongs_to_many is another way to do this.

# 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

Note: You still need the association table in your database but it's just hidden from your models.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文