我正在设计一个应用程序,它有两个 [三个包括管理员] 用户类型:买家和卖家。当用户注册时,假设他们注册只是为了购买东西[买家帐户]。但是,如果他们希望成为卖家,那么他们应该可以选择发布待售商品,[成为卖家]。这变得很重要,因为用户可以在帐户类型之间来回切换。
当然,卖家也可以购买元素。
问题
我面临的问题是卖家有 profile
买家可以查看其待售商品的页面,而买家则不能。但是,两种用户类型都有 My Account
他们可以用来更新他们的信息的页面。
可能的设计选择
单表继承
class User < ActiveRecord::Base
has_one :profile
end
class Seller < User
has_many :sale_items
end
class Buyer < User
# nothing here.. I guess this is the "default" user type
end
我想到了这种方法,因为这样我就可以清楚地区分用户类型。例如,每个用户的显示页面是明确分开的。但是,这可能会导致每个 Controller 中的代码重复,并在用户类型之间切换时引入问题。
只需使用 declarative_authorization 或 CanCan 向基本用户类型添加功能
class User < ActiveRecord::Base
has_one :profile
has_many :sale_items # only for Sellers
# if the user is a seller, allow them to add sale_items
end
我想到了这种方法,因为卖方基本上是具有附加功能的买方,例如发布待售商品。不过,这可能会导致很多 View 逻辑。例如
if @user.role == "seller" render _some_seller_partial
.我也不喜欢在 View 中检查硬编码字符串的想法。好吧,我想我可以做 if @user.seller?
其他设计选择?
我真的很想听听其他人如何为这个应用程序建模。这几天我一直在思考这个问题。
最佳答案
我会使用第二个选项,但使用 declarative_authorization 而不是 cancan,并且我会使用 role_model Gem 将角色存储在用户模型中。
class User < ActiveRecord::Base
has_one :profile
has_many :sale_items # only for Sellers
# if the user is a seller, allow them to add sale_items
# t.integer :roles_mask , :default => 0 # for role_model
end
declarative_authorization 比 CanCan 更强大一点,我发现一旦项目需要更多/更复杂的角色,它可以更好地扩展。
如果您使用 role_model Gem 存储您的角色,它会将它们作为位图存储在 roles_mask 属性中。
这意味着一个用户可以拥有多个角色,例如可以同时是卖家和买家,如果您愿意,也可以是管理员或版主。
看:
http://railscasts.com/episodes/188-declarative-authorization
http://railscasts.com/episodes/189-embedded-association
http://railscasts.com/episodes/192-authorization-with-cancan
http://railscasts.com/episodes/193-tableless-model
和:
http://everydayrails.com/2011/10/06/rails-authorization.html
http://www.tonyamoyal.com/2010/07/28/rails-authentication-with-devise-and-cancan-customizing-devise-controllers/
关于ruby-on-rails - 在 Rails 中处理不同的用户类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7800222/