2010-12-04 75 views
0

我有3個類:用戶,自行車,交易。rails has_many 3個表之間的關聯

用戶可以有很多自行車,而自行車只有一個用戶(所有者)。 本次交易有一輛自行車,和一個用戶(買家)...

在我的用戶模型,我有這些協會:

has_many :bicycles_owned, :class_name => "Bicycle", 
     :uniq => true, :foreign_key => "owner_id" 

has_many :trans_bicycles_bought, :class_name => "Transaction", 
     :foreign_key => "buyer_id" 

has_many :bicycles_bought, :class_name=> "Bicycle", 
     :through => :trans_bicycles_bought, :source => :bicycle 

has_many :trans_bicycles_sold, :class_name => "Transaction", 
     :through => :bicycles_owned, :source => :transaction 

現在我想聯想bicycles_sold ......我已經嘗試了很多事情,但我不能得到正確的代碼..正確的參數...

回答

0

如何:

has_many :bicycles_sold, :class_name => "Bicycle", 
      :finder_sql => 'SELECT b.* FROM bicycles AS b ' + 
         'JOIN users AS u ON u.id = b.owner_id ' + 
         'JOIN transactions AS t ON t.bicycle_id = b.id ' + 
         'WHERE u.id = #{id}' 
+0

Ei!感謝您的回覆......這個sql語句運行良好..但它不好,可讀......有沒有其他的選擇,具有「通過」和「源」屬性? – joao 2010-12-04 19:33:12

0

Here我你可能會感興趣的文章

我不確定Rails 3是否支持嵌套has_many:through,但是2.3.5不支持。 Rails有一張(非常舊的)票。還有一個嵌套的has_many:through插件,它具有2.3.x的實驗分支。我不喜歡使用'實驗'的東西。