2011-03-28 81 views
9

我已經釘牢了我想要的東西,但我似乎無法像鋼軌設計師一樣尋找它。基本上,我有(請留出多元化的/ etc的問題):Has_Many:通過或:finder_sql

人 關係(父母,後代)

我試圖得到一個單親家庭的所有子女,對於許多單親後代(假設每個後代只有一位家長)。

我可以在模型下面的方式做到這一點:

has_one  :parent, :through => :relationships, :foreign_key => :human_id, :source => :source_human 
has_many :offsprings, :finder_sql => 
      'SELECT DISTINCT offsprings.* ' + 
      'FROM humans offsprings INNER JOIN relationships r on ' + 
      'r.human_id = offsprings.id where r.source_human_id = #{id}' 

我不得不這樣做,因爲更好的方式來做到這一點:

has_many :offsprings, :through => :relationships, :foreign_key => :source_human_id, :source => :human 

是不可能的,因爲外鍵在has_many忽略(根據文檔在這裏:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

但是,現在我收到此錯誤:

DEPRECATION WARNING: String-based interpolation of association conditions is deprecated. Please use a proc instead. So, for example, has_many :older_friends, :conditions => 'age > #{age}' should be changed to has_many :older_friends, :conditions => proc { "age > #{age}" }. (called from irb_binding at (irb):1)

但是,無論我怎麼破解:這裏的條件,似乎並沒有:finder_sql想參與。有什麼想法嗎?

回答

35

如果你什麼

has_many :offsprings, :finder_sql => 
      proc { "SELECT DISTINCT offsprings.* " + 
      "FROM humans offsprings INNER JOIN relationships r on " + 
      "r.human_id = offsprings.id where r.source_human_id = #{id}" } 
+2

女士和病菌,獲勝者。文檔在這裏是錯誤的,你不做:條件:finder_sql,你只是建立它。 – aronchick 2011-03-29 19:49:37

4

事實上,我會寫這樣說:

has_many :offsprings, :finder_sql => proc {OFFSPRING_SQL % {id: id}} 

OFFSPRING_SQL = "SELECT DISTINCT offsprings.* 
        FROM humans offsprings 
        INNER JOIN relationships r 
         ON r.human_id = offsprings_id 
         WHERE r.source_human_id = %{id}" 

我認爲它使聯想更容易理解,它使肉眼SQL更容易編輯。它還利用基於字符串的參數插值。