2013-12-09 41 views
1

是否可以進行如下查詢? (僞碼)Rails活動記錄查詢包括委託屬性

u=User.includes(all_delegated_attributes_from_relationships).all 

怎麼樣?

進一步解釋:

class User<ActiveRecord::Base 
    has_one :car 
    delegate :wheel, :brake, :motor, to: :car, prefix: true 
end 

然後:

u=User.includes(delegated_car_parts).all 
#<user id: 1, car_id: 1, name: "John", car_wheel: "foo", car_motor: "bar", car_brake: false> 

我知道,這聽起來有些奇怪,但我有一個功能添加到一箇舊的應用程序導出所有委託屬性一個CSV模型,這個模型有14個關係和300個代表團...我剛剛學到了德米特定律,當我做這個應用程序時...

+0

你是什麼意思的委派屬性? – BroiSatse

+0

你爲什麼想這樣做? –

回答

2

假設輪子,斷開和電機關係ps on car,你可以這樣做:

User.includes(:car => [:wheel, :brake, :motor]).all 
+0

感謝您的回答,這就是我需要得到的答案,但我擁有一個有很多關係和授權的模型,我希望以更方便的方式來完成。 –

+0

似乎有點奇怪。如果您查看代理的源代碼(http://apidock.com/rails/Module/delegate)它會生成方法,但沒有已經委派的方法列表。所以你可以做的最好的就像@BroiSatse的答案。 –

2

沒有內置的方法來做到這一點。你可以嘗試像這樣:

class User < ActiveRecord::Base 
    has_one :car 

    DelegatedCarMethods = [:wheel, :brake, :motor] 
    delegate *DelegatedCarMethods, to: :car, prefix: true 

    scope :with_car_delagations, lambda do 
    select_array = ["#{table_name}.*"] 
    select_array += DelegateCarMethods.map {|method| "#{Car.table_name}.#{method} AS car_#{method}"} 
    select(select_array.join(', ')).joins(:car)   
    end 
end 

但它不是非常漂亮。你爲什麼需要這個?撥打user.wheeluser.motor感覺不對。

+0

謝謝,它可以指向我正確的方向。我需要這樣做,因爲我有一個擁有衆多關係和授權的舊應用程序,客戶向我詢問是否有可能將所有該模型導出爲CSV,並且選擇每個屬性可能非常繁瑣。 –