Search code examples
ruby-on-railsactiverecordhas-scope

How to use has_scope with inherited_resources?


I'm following git wiki for has_scope.

It has an example:

# in model
scope :featured, -> whatever

# in controller
has_scope :by_degree
...
@graduations = apply_scopes(Graduation).all

So did that:

class Account < ActiveRecord::Base
  scope :inactive, -> { where(deleted_at: nil) }
end

class Admin::AccountsController < Admin::BaseController
  has_scope :inactive

  private
  def collection
    apply_scopes(Account)
  end

  def end_of_association_chain
    @end_of_association_chain ||= super.order(created_at: :desc)
  end
end

When accessing collection in the view (like collection.each) - getting this error:

undefined method `each' for #<Class:0x007fbeca533eb0>

It seems to give a class. But I expect it to contain an array of objects.

Tried to add the load method:

collection.load.each ...

But got another error:

wrong number of arguments (0 for 1..2)

Have no idea where to look further. Any ideas?


Solution

  • You did this wrong.

    private
      def collection
        @accounts ||= end_of_association_chain.order(created_at: :desc)
      end
    

    And this is all. Inherited_resources apply scopes automatically inside of end_of_association_chain