has_many与select关联

时间:2012-02-07 16:51:39

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord active-relation

一切! 我想创建额外的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

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

实施例

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

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

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/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'

UPD2

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

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

2 个答案:

答案 0 :(得分:8)

您可以创建relation价格的新select

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

association extension怎么样?

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

然后你可以做@price.orders.just_price

之类的事情

答案 1 :(得分:0)

要在Rails 4及更高版本中执行此操作,请使用以下代码:

has_many :order_prices, -> {
  select('orders.price')
} :through => order_items