如何在Rails 3中将示波器与Ransack一起使用? [英] How can I use scopes with Ransack in Rails 3?

查看:113
本文介绍了如何在Rails 3中将示波器与Ransack一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆