views:

52

answers:

1

I'm trying to chain two named_scopes in my User model.

The first:

  named_scope :commentors, lambda { |*args|
      { :select => 'users.*, count(*) as total_comments',
        :joins => :comments,
        :conditions => { :comments => { :public_comment => 1, :aasm_state => 'posted', :talkboard_user_id => nil} },
        :group => 'users.id',
        :having => ['total_comments > ?', args.first || 0],
        :order => 'total_comments desc' }
      } 

The second:

  named_scope :not_awarded_badge, lambda { |badge_id|
    { :include => :awards,
      :conditions => [ "? not in (select awards.badge_id from awards where awards.user_id = users.id)", badge_id ]
    }
  }

I am trying to chain the two like this:

User.commentors(25).not_awarded_badge(1)

However, I get the following error:

Mysql::Error: Unknown column 'total_comments' in 'order clause': SELECT `users`.`id`...

How can I resolve this issue?

A: 

change

:order => 'total_comments desc'

to

:order => 'count(*) desc'

it should like

 named_scope :commentors, lambda { |*args|
      { :select => 'users.*, count(*) as total_comments',
        :joins => :comments,
        :conditions => { :comments => { :public_comment => 1, :aasm_state => 'posted', :talkboard_user_id => nil} },
        :group => 'users.id',
        :having => ['total_comments > ?', args.first || 0],
        :order => 'count(*) desc' }
      } 
Salil
you have to do the same for :having
keruilin