簡體   English   中英

Rails Active Record查詢,包括委托的屬性

[英]Rails Active Record query including delegated attributes

是否可以進行這樣的查詢? (偽代碼)

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個委派...我剛學習Demeter定律這個程序...

假設車輪,斷裂和電動機與汽車有關,則可以執行以下操作:

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

沒有內置方法可以執行此操作。 您可以嘗試:

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感覺不正確。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM