2010-05-25 145 views
1

我怎样才能变成named_scope?如何将此find_by_sql转换为named_scope?

def self.hero_badge_awardees 
     return User.find_by_sql("select users.*, awards.*, badges.badge_type 
      from users, awards, badges 
      where awards.user_id = users.id and badges.id = awards.badge_id and badges.badge_type = 'HeroBadge'") 
     end 

回答

0
class Badge 
    has_many :awards 
end 

class Award 
    belongs_to :badge 
    belongs_to :user 
end 

class User 
has_many :awards 
has_many :badges, :through => :awards 
named_scope :with_badge, 
    lambda { |badge_type| 
    :include => :badges, 
    :conditions => ["badges.badge_type = ?", badge_type] 
    } 
end 

,那么你可以尝试:

User.with_badge("HeroBadge") 

这看起来像它应该工作给我,但我没有测试它。希望这会给你带来一些东西。

+0

都能跟得上。得到以下错误:语法错误,意外tASSOC,期待'}' – keruilin 2010-05-26 00:57:29

0

具体回答你的问题,试试这个:

class Badge 
    has_many :awards 
end 

class Award 
    belongs_to :badge 
    belongs_to :user 
end 

class User 
    has_many :awards 
    has_many :badges, :through => :awards 

    named_scope :hero_badge_awardees, 
    :include => [:awards, :badges], 
    :conditions => "badges.badge_type = 'HeroBadge'" 
end