开发者

How to Resolve MySQL Error? Chaining Named Scopes

开发者 https://www.devze.com 2022-12-31 07:29 出处:网络
I\'m trying to chain two named_scopes in my User model. The first: named_scope :commentors, lambda { |*args|

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 开发者_StackOverflow中文版=> '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?


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' }
      } 
0

精彩评论

暂无评论...
验证码 换一张
取 消