开发者

rails has_many association between 3 tables

开发者 https://www.devze.com 2023-01-28 04:05 出处:网络
I have 3 classes: User, Bicycle, Transaction. A user can have many bicycles, and bicycle have only one user (owner).

I have 3 classes: User, Bicycle, Transaction.

A user can have many bicycles, and bicycle have only one user (owner). The transaction have one bicycle, and one user (the buyer)...

In my user model I have these associations:

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

Now I want the association bicycles_sold... I already tried a lot of things, but I can't get the right code.. the right ar开发者_JAVA技巧guments...


How about:

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}'


Here is an article you might be interested in.

I’m not sure if Rails 3 supports nested has_many :through, but 2.3.5 does not. There is a (very old) ticket for Rails. There is also a nested has_many :through plugin that is has an experimental branch for 2.3.x. I don’t like using things that are ‘experimental’.

0

精彩评论

暂无评论...
验证码 换一张
取 消