ruby-on-rails – 用户的Rails模型结构
我是rails的新手,我正在开发第二个rails应用程序.
该应用程序将为用户提供不同的角色,但某些用户将拥有多个角色. 该网站的每个用户都是艺术家.一些用户将扮演主持人的角色. 我该如何构建这个?在我使用过的一些PHP应用程序中,只有一个用户,然后是is_admin的数据库列,等等.但我查看了rails应用程序的源代码,并看到了用户和管理员等的单独模型,尽管我我不确定为什么. 那么,我应该有一个带有角色属性的用户模型,可以是主持人,然后在我的视图,路线等中调用用户“艺术家”吗? 或者我应该有一个User模型,一个继承自它的Moderator模型,以及一个belongs_to User的Artist模型? 我真的很困惑. 解决方法
你可以寻找宝石Devise和CanCan.这对真是强大的组合.这使得两个模型User和Role.在角色中,您可以创建新角色,而无需为其创建新模型.虽然它创建了模型能力,但您可以在此处定义角色的访问规则.
手册: 在这里你可以找到Devise和CanCan的来源和wikies: https://github.com/plataformatec/devise https://github.com/ryanb/cancan 我的模型看起来像这样: Role.rb class Role < ActiveRecord::Base has_and_belongs_to_many :users end User.rb class User < ActiveRecord::Base has_many :accounts has_and_belongs_to_many :roles # Include default devise modules. Others available are: # :token_authenticatable,:confirmable,:lockable and :timeoutable devise :database_authenticatable,:recoverable,:rememberable,:trackable,:validatable # Setup accessible (or protected) attributes for your model attr_accessible :email,:username,:password,:password_confirmation,:remember_me,:role_ids def role?(role) return !!self.roles.find_by_name(role.to_s.camelize) end end Ability.rb class Ability include CanCan::Ability def initialize(user) user ||= User.new # guest user if user.role? :administrator can :manage,:all elsif user.role? :operator can :read,Account can :read,Server elsif user.role? :customer can :manage,Server end end end 在控制器中,您必须只添加以下两行: class YourController < ApplicationController before_filter :authenticate_user! load_and_authorize_resource ... end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |