【发布时间】:2012-11-05 22:54:32
【问题描述】:
我正在尝试根据用户的授权获取搜索结果...
【问题讨论】:
标签: ruby-on-rails-3.1 cancan ransack
我正在尝试根据用户的授权获取搜索结果...
【问题讨论】:
标签: ruby-on-rails-3.1 cancan ransack
执行 Ransack 搜索后,只需使用 CanCan 过滤结果。这是我的应用列出提供程序的示例。
如果你的技能不使用方块,请使用accessible_by:
def index
@search = Provider.sorted.search(params[:q])
@providers = @search.result.accessible_by(current_ability)
end
如果你的技能使用方块,你不能使用accessible_by:
def index
@search = Provider.sorted.search(params[:q])
@providers = @search.result.select{|p| can? :read, p}
end
有关更多详细信息和示例,请查看 Fetching Records 上的 cancan wiki
希望有帮助
【讨论】:
sorted 是 Provider 上的命名范围。查看 cancan wiki 上的 Fetching Records,它解释了 accessible_by 是一个作用域,因此它可以与其他作用域链接。
As of 1.4 the index action will load the collection resource using accessible_by
所以现在我们在index 操作中拥有所有可访问的记录。因此以下将起作用
def ProvidersController
before_filter :authenticate_user!
load_and_authorize_resource
def index
@q = @providers.search(params[:q]).page(params[:page])
@providers = @q.result
end
end
【讨论】:
search 现在是 ransack。 CanCanCan 可以过滤 ActiveRecord 关系,如果 load_and_authorize_resource 包含在控制器的顶部,则 @providers 在 index 的条目中保留该关系。
search 方法弃用警告,但它确实有效。我建议开始使用ransack 而不是search