How to translate find_by_sql statement into named_scope?
How do I translate the following into a 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
Here's what I h开发者_运维问答ave right now but it doesn't seem to work:
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"
}
}
Ulimately, this is what worked;
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 problem you have is because you replaced selecting from users, comments
with an inner join with comments
. To properly translate the SQL to a named_scope, use this:
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' } }
And you can't have a default value for lambda parameters, so you can't use |cutoff = 0|
.
精彩评论