如何在Rails 3中将示波器与Ransack一起使用? [英] How can I use scopes with Ransack in Rails 3?
问题描述
在我的Widget模型中,我有以下内容:
In my Widget model I have the following:
scope :accessible_to, lambda { |user|
if user.has_role?('admin')
self.all
else
roles = user.roles
role_ids = []
roles.each { |r| role_ids << r.id }
self.joins(:widget_assignments).where('widget_assignments.role_id' => role_ids)
end
}
理想情况下,我想将此范围用作Ransack搜索结果的过滤器,所以在我的控制器中,我有:
Ideally, I would like to use this scope as a filter for Ransack's search results, so in my controller I have:
def index
@q = Widget.accessible_to(current_user).search(params[:q])
@widgets = @q.result.order('created_at DESC')
end
这样做会产生以下错误:
Doing this generates the following error:
未定义的方法搜索",用于Array:0x007ff9b87a0300
undefined method `search' for Array:0x007ff9b87a0300
我猜想Ransack在寻找ActiveRecord关系对象而不是数组.无论如何,我可以将示波器用作Ransack的筛选器吗?
I'm guessing that Ransack is looking for an ActiveRecord relation object and not an array. Is there anyway that I can use my scope as a filter for Ransack?
推荐答案
将self.all
更改为self.scoped
. all
返回一个数组.
Change the self.all
for self.scoped
. all
returns an array.
Rails 4的更新:all
现在将返回范围.
Update for Rails 4: all
will now return a scope.
这篇关于如何在Rails 3中将示波器与Ransack一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!