1

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

2 回答 2

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")

这看起来应该对我有用,但我还没有测试过。希望这能为您带来一些启发。

于 2010-05-25T23:02:29.200 回答
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
于 2010-05-26T17:03:35.460 回答