Ruby on rails Rails 4:CanCanCan的能力有很多:通过关联
我有一个Rails应用程序,具有以下型号:Ruby on rails Rails 4:CanCanCan的能力有很多:通过关联,ruby-on-rails,ruby-on-rails-4,devise,cancan,cancancan,Ruby On Rails,Ruby On Rails 4,Devise,Cancan,Cancancan,我有一个Rails应用程序,具有以下型号: class User < ActiveRecord::Base has_many :administrations has_many :calendars, through: :administrations end class Calendar < ActiveRecord::Base has_many :administrations has_many :users, through: :administrations
class User < ActiveRecord::Base
has_many :administrations
has_many :calendars, through: :administrations
end
class Calendar < ActiveRecord::Base
has_many :administrations
has_many :users, through: :administrations
end
class Administration < ActiveRecord::Base
belongs_to :user
belongs_to :calendar
end
由于我对Rails不太熟悉,而且这是我第一次使用CanCanCan,因此我对自己的代码不是很有信心,希望得到一些验证或改进建议
那么,这段代码能工作吗?它能让我实现我所需要的吗
更新:使用当前代码,当我以用户身份登录并访问另一用户日历的“日历显示”页面时,我实际上可以访问日历,但我不应该访问
所以,很明显,我的代码不起作用
知道我做错了什么吗
更新2:我认为我的代码中有错误,因为我使用的是:model
而不是model
,以允许用户对给定的模型执行操作
但是,代码仍然不起作用
你知道这里可能出了什么问题吗
更新3:问题是否是因为我使用if user.role?(:owner)
检查用户的角色是否设置为owner,而在数据库中角色实际上定义为“owner”(作为字符串)
更新4:我一直在做一些研究,我意识到我犯了两个错误
我没有向日历
和管理
控制器添加加载和授权资源
我已经定义了两个属性两个参数-initialize(user,calendar)
-而不是我的initialize
方法中的一个
因此,更新了两个控制器以及ability.rb文件,如下所示:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.role?(:owner)
can :manage, Calendar, :user_id => user.id
can :manage, Administration, :user_id => user.id
can :manage, Administration, :calendar_id => calendar.id
elsif user.role?(:editor)
can [:read, :update], Calendar, :user_id => user.id
can :destroy, Administration, :user_id => user.id
elsif user.role?(:viewer)
can [:read], Calendar, :user_id => user.id
can :destroy, Administration, :user_id => user.id
end
end
end
现在,当我尝试访问不属于当前用户的日历时,我得到以下错误:
NoMethodError in CalendarsController#show
undefined method `role?' for #<User:0x007fd003dff860>
def initialize(user)
user ||= User.new
if user.role?(:owner)
can :manage, Calendar, :user_id => user.id
can :manage, Administration, :user_id => user.id
can :manage, Administration, :calendar_id => calendar.id
日历控制器中的命名错误显示
未定义的方法“角色”#
def初始化(用户)
user | |=user.new
if user.role?(:所有者)
can:manage,Calendar,:user\u id=>user.id
can:manage,Administration,:user\u id=>user.id
can:manage,Administration,:calendar\u id=>calendar.id
如何解决这个问题?没有这样的方法角色?
用户模型。Cancancan文档错误地假设示例中存在这样的方法
要解决此问题,您应该执行以下操作:
if user.role == 'Owner'
...
elsif user.role == 'Editor'
...
elsif user.role == 'Viewer'
...
这正是我最后要做的。谢谢
if user.role == 'Owner'
...
elsif user.role == 'Editor'
...
elsif user.role == 'Viewer'
...