【问题标题】:How transform this find_by_sql to named_scope?如何将此 find_by_sql 转换为 named_scope?
【发布时间】:2010-05-25 22:28:58
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:
    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")
    

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

    【讨论】:

    • 不。得到以下错误:语法错误,意外 tASSOC,期待 '}'
    【解决方案2】:

    要具体回答您的问题,请尝试以下操作:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-14
      • 2015-10-02
      • 2011-02-23
      相关资源
      最近更新 更多