22

I have the following models:

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

I am trying to join everything together into an sql in the form of activerecord, but I'm not sure how to go about doing it because I'm relatively new to 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

The key problem for me is the second link where goods_movement date == price_movement date. Can someone advice on whether there's any way to do it?

mingsheng
  • 223
  • 1
  • 2
  • 4

1 Answers1

35
Company.joins(:price_movements,:goods_movements).where("goods_movement.date = price_movement.date")

Go through this link it has detailed explanation of how to use ActiveRecord

Rimian
  • 36,864
  • 16
  • 117
  • 117
Siva
  • 7,780
  • 6
  • 47
  • 54
  • 2
    Just an additional question: In terms of efficiency, because the two tables are huge to begin with, this ActiveRecord query takes 8000ms compared to the sql that completes in 3000ms. Is there any ways to speed things up a little in ActiveRecord? I am using ActiveRecord::Base.connection.execute() in the latter. – mingsheng Jan 13 '14 at 04:43
  • 1
    What would be the way to go about getting the records from PriceMovement and GoodsMovement where Company id is 1? – Qaiser Wali Mar 25 '18 at 06:57