如何将find_by_sql语句翻译成named_scope?

时间:2010-05-24 21:51:50

标签: sql ruby-on-rails named-scope

如何将以下内容翻译成named_scope?

  def self.commentors(cutoff=0)
    return User.find_by_sql("select users.*, count(*) as total_comments from users, comments 
      where (users.id = comments.user_id) and (comments.public_comment = 1) and (comments.aasm_state = 'posted') and (comments.talkboard_user_id is null) 
      group by users.id having total_comments > #{cutoff} order by total_comments desc")
  end

这是我现在所拥有的,但它似乎不起作用:

  named_scope :commentors, lambda { |count=0|
    { :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 > #{count.to_i}",
      :order => "total_comments desc"
    }
  }

毫无疑问,这是有效的;

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

1 个答案:

答案 0 :(得分:0)

您遇到的问题是,您使用users, comments替换了comments内部联接的选择。要将SQL正确转换为named_scope,请使用:

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

并且你没有lambda参数的默认值,因此你不能使用|cutoff = 0|