我有一个带有users、articles和collaborations的Rails应用程序。下面是几种关系:
User has_many :articles
User has_many :collaborations
Article belongs_to :users
Article has_many :collaborations
# Collaboration has collaboration.id collaboration.user_id and collaboration.article_id.
Collaboration belongs_to :users
Collaboration belongs_to :articles通过合作,我能够成功地访问用户和文章,所以我认为我的应用程序中的所有设置都是正确的。好的,在问题上。
我使用的是CanCan,角色是:admin。基本上,我只希望:admin能够创建帖子和协作,而且我的工作也是正确的。is...how的问题是,我是否将该角色写入我的ability.rb文件,以便非管理员的用户仍然可以在他们参与协作的文章上进行协作?“
我应该如何用ability.rb写这个。这就像我想说的:“不是管理员的用户可以管理文章,如果他们是文章协作的一部分。”
对不起,我还没喝咖啡。)这是我的ability.rb。
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user
if user.role == "admin"
can :manage, :all
else
can :read, Article
# this is where I want to say: can :manage if part of collaboration for article
end
end
end发布于 2012-10-07 23:45:45
以下是您能力类中可能对您有用的逻辑:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user
case
when user.admin?
can :manage, :all
when user.registered?
can :read, Article
can :manage, Article, :collaborations => { :user_id => user.id }
else # user.guest?
can :read, Article
end
end
endCanCan允许您指定关联的条件;在这里,我们传递Article上的:collaborations关联的:user_id条件。
添加到用户的其他方法:
class User < ActiveRecord::Base
ROLES = [
ADMIN = 'admin'
]
def admin?
role == ADMIN
end
def registered?
persisted?
end
end为了确保这是正确的,下面是如何使用RSpec、FactoryGirl和CanCan matchers编写测试:
require 'spec_helper'
require "cancan/matchers"
describe Ability do
subject { Ability.new(user) }
context "admin" do
let(:user) { create(:admin) }
it { should be_able_to(:manage, :all) }
end
context "user" do
let(:user) { create(:user) }
it { should be_able_to(:read, Article) }
it "cannot manage articles without collaborations" do
article = create(:article)
should_not be_able_to(:manage, article)
end
it "cannot manage articles only others collaborated on" do
article = create(:article)
article.collaborations.create { |c| c.user = create(:user) }
should_not be_able_to(:manage, article)
end
it "can manage article with collobaration" do
article = create(:article)
article.collaborations.create { |c| c.user = user }
should be_able_to(:manage, article)
end
end
context "guest" do
let(:user) { User.new }
it { should be_able_to(:read, Article) }
it { should_not be_able_to(:manage, Article) }
end
end发布于 2012-10-08 13:08:38
您可以在ability.rb文件中尝试这样的操作,.Just定义用户表中的角色,并在模型文件中使用
角色、“行政”、“客人”、“其他”
if user.role == "Admin"
if user.role == "admin"
can :manage, :all
else
can :read, Article
end
end发布于 2012-10-05 13:41:17
试一试
can :manage, Article, :collaborations => {:user_id => user.id}https://stackoverflow.com/questions/12747313
复制相似问题