私は現在、必要な各条件に応じて CanCan の役割を分離する方法にこだわっています。私たちのアプリケーションには、多くのカテゴリ (数学、英語、歴史など) があり、それぞれに多くのコースがあります。
各ユーザーは、各カテゴリでさまざまな役割を持つことができます。たとえば、ジョンは数学の「リーダー」になることができます。つまり、彼は数学のすべてのコースを読むことができます。ジョンは英語の「ライター」になることもできます。つまり、彼は英語ですべてのコースを読んだり、英語のカテゴリ内でコースを作成したり、英語で作成したコースのみを編集/削除したりできます。
これらの役割だけが John の役割である場合、John はナビゲーション バーでカテゴリの履歴を表示できず、履歴内のコースへのアクセスが拒否されます。
リレーションの設定方法は次のとおりです。
class User < ActiveRecord::Base
has_many :roles
def has_role?(role_sym)
roles.any? { |r| r.level.underscore.to_sym == role_sym }
end
end
class Category < ActiveRecord::Base
has_many :roles
has_many :courses
end
class Role < ActiveRecord::Base
belongs_to :user
belongs_to :category
attr_accessible :level, :category_id, :user_id
end
model/ability.rb には
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in) #guest
if user.has_role? :reader
reader(user)
end
if user.has_role? :writer
writer(user)
end
end
#BE ABLE TO SEE COURSES AND CATS FOR PERMITTED CATS.
def reader(user)
can :read, Category, :roles => { :user_id => user.id, :level => "reader" }
## how would we be able to limit reading of courses that are within permitted categories? something like category.courses ~~
end
def writer(user)
reader(user) #inheriting from reader? this doesnt work because level is hardcoded into reader
can :read, Category, :roles => { :user_id => user.id, :level => "writer"}
# 1.you can read all courses in category that you are given permission to
# 2.you can write courses in permitted category
# 3.you can edit, delete courses that only youve created within permitted category
end
end
質問:
「読み手」と「書き手」の役割を正しく分けるにはどうすればよいでしょうか。アクセスできるカテゴリ内のコースにアクセスするにはどうすればよいですか?
capacity.rb でリーダーとライターのメソッドを定義した後、それらをビュー ページでどのように使用するのでしょうか? 現在のドキュメントでは "<% if can? :read, @category %> " のようなものを使用しているようですが、それは私たちが分離して定義したメソッドを使用していません。
ps ゲスト、リーダー、ライター、エディター、マネージャー、管理者、app_admin (開発者) の 7 つの異なる役割があります。
私はこれを 3 日間解決しようとしてきました - 私はまだかなりの初心者であることを理解してください! 前もって感謝します