【问题标题】:has_many association with selecthas_many 与 select 的关联
【发布时间】: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


    【解决方案1】:

    您可以创建一个新的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

    【讨论】:

    • 谢谢!有用 !但是当我在包含它时使用它会引发错误(更新的问题
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-05-21
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      相关资源
      最近更新 更多