1

I'm attempting to share a named scope between two models via a module. It is not working for me. I keep getting an undefined error. I'm trying with an empty 'your_scope' scope:

config/initializers/boxshare_init.rb

require 'assets/named_scopes/m.rb'

lib/assets/named_scopes/m.rb

module M
  def self.included(base)
    base.class_eval do
      scope :your_scope, lambda {}
    end
  end
end

app/models/folder.rb

class Folder < ActiveRecord::Base       
    include M

    acts_as_tree

    belongs_to :user
    has_many :assets, dependent: :destroy
end

rails console: $ rails c

Loading development environment (Rails 4.1.1) irb: warn: can't alias
context from irb_context.
2.0.0-p0 :001 > Folder.last.your_scope  
Folder Load (0.1ms)  SELECT  "folders".* FROM "folders"   ORDER BY "folders"."id" DESC LIMIT 1
NoMethodError: undefined method `your_scope' for <Folder:0x007fd781a1daf0>

Where am I going wrong?

Starkers
  • 9,083
  • 14
  • 82
  • 143
  • 1
    You should use Concerns http://stackoverflow.com/questions/14541823/how-to-use-concerns-in-rails-4 – Rafal Jun 25 '14 at 14:38

1 Answers1

0

The ActiveRecord's method .last returns an instance of your model, not an AR::Relation that you can chain scopes on it.

Try this:

Folder.last.class
# => Folder
Folder.your_scope.class
# => ActiveRecord::Relation

Use your_scope like this:

Folder.your_scope.last
MrYoshiji
  • 51,182
  • 12
  • 115
  • 106