我正在创建一个非常简单的基于wiki的网站,用户可以在其中升级和降级其帐户。成为高级'的特权之一。 member是能够创建私人wiki的。
我遇到的问题是在我的wikis_controller.rb中处理这段代码:
def index
@wiki = Wiki.visible_to(current_user)
@wikis = policy_scope(Wiki)
end
当代码编写时,我收到一条错误消息'undefined method 'visible_to'
。但是,如果我在该方法中注释掉第一行,那么它看起来像这样:
def index
#@wiki = Wiki.visible_to(current_user)
@wikis = policy_scope(Wiki)
end
用户可以看到wiki索引,但是他们无法看到他们的私人wiki。
我出错的任何想法?作为参考,这是我的wiki_policy.rb:
class WikiPolicy < ApplicationPolicy
attr_reader :user, :record
def initialize(user, record)
@user = user
@record = record
end
def update?
user.present?
end
class Scope
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
wikis = []
if user.role == 'admin'
wikis = scope.all # if the user is an admin, show them all the wikis
elsif user.role == 'premium'
all_wikis = scope.all
all_wikis.each do |wiki|
if !wiki.private? || wiki.user == user || wiki.users.include?(user)
wikis << wiki # if the user is premium, only show them public wikis, or that private wikis they created, or private wikis they are a collaborator on
end
end
else # this is the lowly standard user
all_wikis = scope.all
wikis = []
all_wikis.each do |wiki|
if !wiki.private? || wiki.users.include?(user)
wikis << wiki # only show standard users public wikis and private wikis they are a collaborator on
end
end
end
wikis # return the wikis array we've built up
end
end
end
这是我的application_policy.rb:
class ApplicationPolicy
attr_reader :user, :record
def initialize(user, record)
@user = user
@record = record
end
def index?
end
def show?
if user.standard?
true
else
false
end
end
def downgrade?
if user.premium?
true
else
false
end
end
def create?
if user.present?
true
else
false
end
end
def new?
create?
end
def update?
user.present?
end
def edit?
update?
end
def destroy?
if user.present? && user.admin? #|| record.user == user)
true
else
false
end
end
def scope
Pundit.policy_scope!(user, record.class)
end
class Scope
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
scope
end
end
end
非常感谢。
答案 0 :(得分:2)
但即使我向Wiki控制器添加'visible_to'方法,我仍然会收到相同的错误消息。
在没有看到您的代码的情况下,我无法确定,但我确定您的问题是,当您要定义类方法时,您正在定义实例方法 强>
你可能正在这样做:
class Wiki
# instance method
def visible_to test
puts test
end
end
允许您调用实例方法:
之类的函数irb(main):018:0> Wiki.new.visible_to "hello world"
# hello world
irb(main):007:0> Wiki.visible_to "hello world"
# NoMethodError: undefined method `visible_to' for Wiki:Class
但是因为你实际上正在调用函数,就像类方法:
Wiki.visible_to(current_user)
你需要像这样定义你的方法:
class Wiki
# class method
def self.visible_to test
puts test
end
end
现在您可以调用类方法:
irb(main):024:0> Wiki.visible_to "hello world"
# hello world
irb(main):007:0> Wiki.new.visible_to "hello world"
# NoMethodError: undefined method `visible_to' for #<Wiki:0x00000001d16a68>