【发布时间】:2012-02-07 16:51:38
【问题描述】:
全部! 我想创建额外的 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 显示带有源选项的示例! 没关系,但是当我在 include 中使用此功能时,它不起作用。
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
我意识到问题,如果你想在includes方法中使用这样的关联,还要添加primary_key选择,否则AR不知道谁是记录的所有者。
has_many :orders, :through => :order_items, :select=>"id, price"
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 activerecord active-relation