【问题标题】:Rails - Joining multiple tablesRails - 加入多个表
【发布时间】:2014-01-13 03:56:51
【问题描述】:

我有以下型号:

class Company < ActiveRecord::Base
  has_many :price_movements
  has_many :goods_movements
end

class PriceMovement < ActiveRecord::Base
  belongs_to :company
end

class GoodsMovement < ActiveRecord::Base
   belongs_to :company
end

我正在尝试以 activerecord 的形式将所有内容合并到一个 sql 中,但我不确定如何去做,因为我对 ROR 比较陌生。

select * from companies c

inner join price_movements p
on c.id = p.company_id

inner join goods_movements g
on c.id = g.company_id
and g.date = p.date

对我来说关键问题是第二个链接,其中商品_移动日期 == 价格_移动日期。 有人可以建议是否有办法做到这一点?

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-4


    【解决方案1】:
    Company.joins(:price_movements,:goods_movements).where("goods_movement.date = price_movement.date")
    

    浏览this link里面有详细的说明ActiveRecord的使用方法

    【讨论】:

    • 只是一个额外的问题:在效率方面,因为这两个表一开始就很大,所以这个ActiveRecord查询需要8000ms,而sql需要3000ms。有什么方法可以加快 ActiveRecord 的速度吗?我在后者中使用 ActiveRecord::Base.connection.execute()。
    • 从 PriceMovement 和 GoodsMovement 中获取 Company id 为 1 的记录的方法是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多