[英]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.