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

だからそれは今動作します。しかし、:orders のように機能する関連付けを作成したいのですが、:select オプションがあります。

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

しかし、現在の :orders accociation をオーバーライドしたくありません。これを行う方法?

ソースオプションを使用したUPDアゾトショーの例!大丈夫ですが、この付属物を includes で使用すると機能しません。

 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

インクルード メソッドでそのような関連付けを使用する場合、primary_key の選択も追加すると、AR は誰がレコードの所有者であるかがわからないという問題に気付きました。

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

2 に答える 2

8

relation価格を抑えた新作が作れますselect

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

また

アソシエーション拡張機能はどうですか?.

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

次に、次のようなことができます@price.orders.just_price

于 2012-02-07T18:18:19.937 に答える