我会推荐以下内容:
Developer 是一个 User 对象。 在架构中使用 is_developer 布尔值区分开发人员和用户。这将使用户/开发人员的集成变得更加容易(没有 switch 语句)。您可以添加命名范围以专门查找开发人员:
class User < ActiveRecord::Base
named_scope :regular_users, :conditions => { :is_developer => false }
named_scope :developers, :conditios => { :is_developer => true }
#you can then call User.regular_users or User.developers
end
或者,您可以让用户/开发人员作为多态关联工作。例如
class Role < ActiveRecord::Base
belongs_to :entity, :polymorphic => true #with entity_id / entity_type in your schema
end
这种方法的缺点是它会使您的代码更加复杂,而语义增益很少或为零。
我并不真正理解您所说的默认权限是什么意思,但这似乎是一个与数据库相反的逻辑问题。每个人都有默认权限吗?然后你可以在 *after_create* 上添加它,或者在编写逻辑时,假设它是真的(或由布尔标志控制)。以下代码将为每个用户创建一个权限,创建后默认为true(对于现有用户,您可以通过手动/ rake任务添加权限)。
class User < ActiveRecord::Base
after_create :add_default_permission
def add_default_permission
Permission.default_permissions.each do |permission|
self.app_permissions.create(:permission_id => permission.id)
end
end
end
至于 default_permissions,我建议在权限表上使用 *is_default* 布尔值。这样,您可以拥有多个默认权限(或稍后删除默认权限)。作为默认权限是权限,无需区分对象模型。即
class Permission < ActiveRecord::Base
named_scope :default_permissions, :conditions => { :is_default => true }
end
最后,确保完整拼写出所有的 ActiveRecord 关联,即
class User < ActiveRecord::Base
has_many :apps
has_many :permissions, :through => :app_permissions, :as => :permissible #edited
end
class App < ActiveRecord::Base
belongs_to :app_permission
has_many :permissions, :through => :app_permissions, :as => :permissible #edited
end
class Permission < ActiveRecord::Base
belongs_to :app_permissions
belongs_to :permissible, :through => :app_permissions, :polymorphic => true #edited
end
class AppPermission < ActiveRecord::Base
belongs_to :permissible, :polymorphic => true #edited
belongs_to :app
end
当用户安装应用程序时:以下为多态性编辑
Class User < ActiveRecord::Base
def get_required_app(app)
required_permissions = []
app.permissions.each do |p|
if self.permissions.find(:first, conditions => { :permission_id => p.id } ).nil?
required_permissions.push p
end
end
required_permissions
end
def install_app(app)
req = required_permissions app
return req if req.count > 0
#add user app
end
end
希望这可以帮助您解决问题,如果您需要任何其他信息,请告诉我。