How can I use scopes with Ransack in Rails 3?
Asked Answered
Q

1

5

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?

Quartered answered 10/1, 2012 at 15:6 Comment(1)
Not related to your actual question, but the second half of your scope could probably be easily written as joins(:widget_assignments).where('widget_assignments.role_id' => user.role_ids)? or user.roles.fetch(:id)? I could be wrong though :)Blakney
H
8

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

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

Harpsichord answered 10/1, 2012 at 17:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.