[英]Correct Associations Ruby on Rails
有人可以帮我纠正我的联想吗?
我有以下型号:
User, Developer, Application, Comments, Rating, Permission
要求:
A user can be a Developer or not.
A user can have Default Permissions and Permissions for each application
A user can install multiple Applications
A user can comment and rate multiple Applications
A developer can develop multiple applications
An application can request a list of permissions.
我已经创建了一些关联,但我相信它不是 100% 正确或存在更简单的方法。
有人可以建议我正确的方法吗?
您将模型与授权混淆了。
您应该查看 CanCan 以获得基于角色的授权。 例如,您不需要开发人员 model,因为它只是具有不同角色/权限的用户。
编辑:将“基于角色的身份验证”更改为“基于角色的授权”。 正如下面的评论指出了身份验证和授权之间的区别。
我认为这就是您想要的 model 工作。 您可以使用连接 model 来管理您的应用程序权限,并使用 Rails STI 来管理每种类型的用户可以做什么,无论是否正在开发。
用户.rb
class User < ActiveRecord::Base
has_many :apps
has_many :comments, :through => :user_comments
has_many :ratings, :through => :user_ratings
end
评论.rb
class Comment < ActiveRecord::Base
belongs_to :user
end
评级.rb
class Rating < ActiveRecord::Base
belongs_to :user
end
用户评论.rb
class UserComment < ActiveRecord::Base
belongs_to :app
end
user_rating.rb
class UserRating < ActiveRecord::Base
belongs_to :app
end
normal_user.rb (STI)
class NormalUser < User
end
开发人员.rb (STI)
class Developer < User
end
应用程序.rb
class App < ActiveRecord::Base
has_many :permissions, :through => :app_permissions
has_many :user_comments
has_many :user_ratings
end
权限.rb
class Permission < ActiveRecord::Base
belongs_to :app
end
app_permission.rb
class AppPermission < ActiveRecord::Base
end
我同意@Mark,不要使用 STI。 更好的方法将按照@Chris Barretto 的建议实施,STI 除外,并使用CanCan进行基于角色的身份验证。 用户 model 的更改将是:
class User < ActiveRecord::Base
has_many :apps
has_many :comments, :through => :user_comments
has_many :ratings, :through => :user_ratings
has_many :roles
end
并且将有另一个 model 用于角色:
class Role < ActiveRecord::Base
has_many :users
end
如果您使用Devise之类的 gem 进行身份验证,那将非常容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.