简体   繁体   中英

Raw SQL to named_scope

How can I turn this raw SQL into a named_scope?

select d.*, count(*) shots_count
   from  duels d, duel_shots ds
   where d.id = ds.duel_id
   group by d.id
   having (d.shots = 1 and shots_count >= 2) or (d.shots = 3 and shots_count >= 6)

I think you want a join, by the way. Give this a go:

class Duel < ActiveRecord::Base
  has_many :duel_shots

  named_scope :blah,
    :select => 'duels.*, count(duels.id) shots_count',
    :joins => :duel_shots,
    :group => 'duels.id',
    :having => '(duels.shots = 1 AND shots_count >= 2) OR (duels.shots = 3 AND shots_count >= 6)'

end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM