2010-05-02 46 views
0

我有三個型號:named_scope或find_by_sql?

  • 用戶
  • 獎盃

的關聯是:

  • 用戶擁有衆多獎項
  • 獎盃有許多獎項
  • 獎屬於用戶
  • 獎屬於獎盃
  • 用戶已經通過獎勵

許多獎盃因此,user_id是在獎勵FK,和trophy_id是在獎勵FK。

在Trophy模型中,這是一個STI模型,它有一個trophy_type列。我想返回已經獲得特定獎盃的用戶列表 - (trophy_type ='GoldTrophy')。用戶可以多次被授予同一獎盃。 (我不想要明顯的結果。)

我可以使用named_scope嗎?如何鏈接他們?或者我需要使用find_by_sql?無論哪種方式,我將如何編碼?

回答

0

我總是用 「的find_by_sql」 舒服你可以用它 使用的find_by_sql如下

User.find_by_sql("select u.id, u.name, t.trophy_type 
        from users u, awards a, trophies t 
        where a.user_id=u.id and 
        t.trophy_id=a.id and 
        t.trophy_type = 'GoldTrophy'" 
       ) 

我不知道用 「named_scope」 可是試試這個

class User < ActiveRecord::Base 

    named_scope :gold_trophy_holder, 
       :select=>" users.id, users.name, trophies.trophy_type",  
       :joins => :awards, "LEFT JOIN awards ON awards.id = trophies.award_id" 
       :conditions => ['trophies.trophy_type = ?', 'GoldTrophy'] 

end 
1

如果您想沿着named_scope路線走,您可以執行以下操作:

添加的has_many:用戶獎盃,如:

has_many :users, :through => :awards 

而下面named_scope:

named_scope :gold, :conditions => { :trophy_type => 'GoldTrophy' } 

您可以撥打以下:

Trophy.gold.first.users 

你需要調用「 .first',因爲named_scope將返回一個集合。不理想。也就是說,就你而言,使用find_by_sql或named_scope可能是完全合適的。如何使用良好的舊版本:

Trophy.find_by_trophy_type('GoldTrophy').users 

這將完全按照您的要求進行,而無需深入研究SQL。