How can I use scopes with Ransack in Rails 3?

女生的网名这么多〃 提交于 2019-12-06 02:58:04

问题


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
}

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:

undefined method `search' for Array:0x007ff9b87a0300

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?


回答1:


Change the self.all for self.scoped. all returns an array.

Update for Rails 4: all will now return a scope.



来源:https://stackoverflow.com/questions/8805426/how-can-i-use-scopes-with-ransack-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!