Scope in Rails 4

I noticed that in most cases you are basically passing a sentence or lambda. But I am trying to do something like this and it doesn'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?

+3


source to share


1 answer


The body of the scope needs to 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')
}

      

+4


source







All Articles