3

all! I want to create additional has_many relation to select only needed columns

Example

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

so it works now. But I would like to create association which works like :orders, but have :select option

Example

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

But I don't want to override current :orders accociation. How to do this?

UPD Azoto show example with source option! It's ok, but when I use this accotiation in includes , it doesn't work.

 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

I realized problem, if you want to use such assotioation in includes method, also add primary_key selection, otherway AR don't know who is an owner of record.

has_many :orders, :through => :order_items, :select=>"id, price"
Fivell
  • 11,829
  • 3
  • 61
  • 99

2 Answers2

8

You can create a new relation that does select price.

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

OR

How about an association extension?.

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

Then you could do something like @price.orders.just_price

Azolo
  • 4,353
  • 1
  • 23
  • 31
0

To do this in Rails 4 and after, use the following code:

has_many :order_prices, -> {
  select('orders.price')
} :through => order_items
Ceasar
  • 22,185
  • 15
  • 64
  • 83