如何将find_by_sql转换为named_scope?

发布于 2024-09-03 03:24:07 字数 319 浏览 6 评论 0原文

我怎样才能变成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

How can I possibly turn into 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

栖竹 2024-09-10 03:24:07
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")

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

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

then you can try:

User.with_badge("HeroBadge")

This looks like it should work to me, but I haven't tested it. Hopefully this sparks something for you though.

随波逐流 2024-09-10 03:24:07

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

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

To specifically answer your question, try this:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文