Rails - Joining multiple tables

落花浮王杯 提交于 2019-12-20 11:50:55

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/21083625/rails-joining-multiple-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!