2012-07-09 22 views
0
User 
# 

Cars 
belongs_to :father, :class_name => "User" 
belongs_to :user 

user = User.find(1) 

夥計們的幫助,我可以通過鍵入user.cars(使用user_id搜索汽車)得到了用戶的汽車,但我可以得到究竟怎麼使用father_id搜索?的has_many多個外鍵搜索

顯然我可以做一個Car.find_by_creator_id(...),但我想知道是否有鐵路解決方案。

感謝

回答

1

可以建立關係的另一面,並指定:inverse_of每個在User模型。像

class User < ActiveRecord::Base 
    has_many :father_cars, :class_name => "Car", :inverse_of => :father 
    has_many :cars, :inverse_of => :user 

    # ... 
end 

Cars < ActiveRecord::Base 
    belongs_to :father, :class_name => "User", :inverse_of => :father_cars 
    belongs_to :user, :inverse_of => :cars 

    # ... 
end 

東西,你就可以訪問與

u = User.find(1) 
cars = user.father_cars 
:father關係