Search code examples
ruby-on-railsruby-on-rails-3scopeargument-error

Argument Error: The scope body needs to be callable


I'm working through the 'Ruby On Rails 3 Essential Training' and have received a problem when using name scopes. When finding records and using queries withing the Rails console everything went smoothly until I tried to use a name scope in my subject.rb file. This is my code in the subject.rb file.

class Subject < ActiveRecord::Base
    
  scope :visible, where(:visible => true)

end   

I saved the .rb file and restarted my Rails console but when I run from my rails console:

subjects = Subject.visible

I get: ArgumentError: The scope body needs to be callable.

Does anyone know why I'm getting this error.


Solution

  • The scope's body needs to be wrapped in something callable like a Proc or Lambda:

    scope :visible, -> {
      where(:visible => true)
    }
    

    The reason for this is that it ensures the contents of the block is evaluated each time the scope is used.