如何将find_by_sql转换为named_scope?

时间:2010-05-25 22:28:59

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

我怎么可能变成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

2 个答案:

答案 0 :(得分: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")

这看起来应该对我有用,但我还没有测试过。希望这会为你带来一些东西。

答案 1 :(得分: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