全部!我想创建额外的 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 Azoto 显示带有源选项的示例!没关系,但是当我在 contains 中使用此功能时,它不起作用。
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 方法中使用这样的关联,还要添加 primary_key 选择,否则 AR 不知道谁是记录的所有者。
has_many :orders, :through => :order_items, :select=>"id, price"