gary1410
gary1410

Reputation: 317

Scoping in Rails 4

I noticed in most of the scoping you mostly pass a where clause or a lambda. But I'm trying to do something like this and it won't work

class LesleyGrade < ActiveRecord::Base
  scope :my_scope, select('STC_TERM_GPA, max(TERM), max(last), max(first)').group('STC_TERM_GPA').order('max(first), max(term) ASC')

end

Just for reference here's my table:

Lesley Grade
------------
id
first
last
stc_term_gpa
term

When I called LesleyGrade.term_gpa this is what I get:

  LesleyGrade Load (27.9ms)  SELECT STC_TERM_GPA, max(TERM), max(last), max(first) FROM "lesley_grades"  GROUP BY STC_TERM_GPA  ORDER BY max(first), max(term) ASC
NoMethodError: undefined method `call' for #<LesleyGrade::ActiveRecord_Relation:0x007fdf9ab13d08>
from /Users/garytsai/.rbenv/versions/2.0.0-p643/lib/ruby/gems/2.0.0/gems/activerecord-4.1.1/lib/active_record/relation/delegation.rb:136:in `method_missing'

Does anyone have any solutions for this?

Upvotes: 3

Views: 40

Answers (1)

infused
infused

Reputation: 24367

The scope body must be wrapped in a proc or lambda, so just change it to:

scope :my_scope, -> { 
  select('STC_TERM_GPA, max(TERM), max(last), max(first)').group('STC_TERM_GPA').order('max(first), max(term) ASC')
}

Upvotes: 4

Related Questions