has_many与select关联

Fiv*_*ell 3 ruby activerecord ruby-on-rails active-relation ruby-on-rails-3

所有!我想创建额外的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
Run Code Online (Sandbox Code Playgroud)

所以它现在有效.但我想创建一个类似于:orders的关联,但有:select选项

has_many :orders, :through => :order_items, :select=>"price"
Run Code Online (Sandbox Code Playgroud)

但我不想覆盖当前:订单协议.这该怎么做?

UPD Azoto显示带有源选项的示例!没关系,但是当我在include中使用这个accotiation时,它不起作用.

 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/ruby-1.9.2-p180@new/gems/activerecord-3.2.1/lib/active_record/associations/preloader/association.rb:88:in `block in associated_records_by_owner'
Run Code Online (Sandbox Code Playgroud)

UPD2

我意识到问题,如果你想在include方法中使用这样的assotioation,还要添加primary_key选择,否则AR不知道谁是记录的拥有者.

has_many :orders, :through => :order_items, :select=>"id, price"
Run Code Online (Sandbox Code Playgroud)

Azo*_*olo 8

您可以创建一个新的relation,做select的代价.

has_many :price_of_orders, :through => :order_items,
                           :source => orders,
                           :select => :price
Run Code Online (Sandbox Code Playgroud)

要么

怎么样的关联扩展

has_many :orders, :through => :order_items do
  def just_price
    select(:price)
  end
end
Run Code Online (Sandbox Code Playgroud)

然后你可以做类似的事情 @price.orders.just_price