3

關聯! 我想創建額外的has_many關係,只選擇需要的列has_many與選擇

class Price < ActiveRecord::Base 
    self.table_name = "pricelist_prices" 
    has_many :order_items, :primary_key=> :city_id, :foreign_key=> :city_id 
    has_many :orders, :through => :order_items 
end 

所以現在的工作。不過,我想創建協會,工作方式類似:訂單,但有:選擇選項

has_many :orders, :through => :order_items, :select=>"price" 

但我不希望重寫電流:訂單accociation。 如何做到這一點?

UPD Azoto顯示帶源選項的示例! 沒關係,但是當我在包含中使用這種標記時,它不起作用。

Price.where(:id=>[12759,12758]).includes(:prices_from_orders) 
    (Object doesn't support #inspect) 

    Price.where(:id=>[12759,12758]).includes(:prices_from_orders).first 
NoMethodError: undefined method `each' for nil:NilClass 
    from /Users/igorfedoronchuk/.rvm/gems/[email protected]/gems/activerecord-3.2.1/lib/active_record/associations/preloader/association.rb:88:in `block in associated_records_by_owner' 

UPD2

我意識到問題,如果你想用這種assotioation在包括方法,還加primary_key選擇,otherway AR不知道誰是創紀錄的擁有者。

has_many :orders, :through => :order_items, :select=>"id, price" 

回答

7

您可以創建一個新的relation,做select價格。

has_many :price_of_orders, :through => :order_items, 
          :source => orders, 
          :select => :price 

OR

怎麼樣的association extension

has_many :orders, :through => :order_items do 
    def just_price 
    select(:price) 
    end 
end 

然後,你可以做這樣的事情@price.orders.just_price

+0

的感謝!有用 !但是,當我在include中使用它時會引發一個錯誤( 更新的問題 – Fivell 2012-02-08 09:13:01