Ruby-on-rails Rails - 加入多个表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21083625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:13:07  来源:igfitidea点击:

Rails - Joining multiple tables

ruby-on-railsactiverecordruby-on-rails-4

提问by mingsheng

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.

我试图以 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

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?

对我来说,关键问题是第二个链接,其中goods_movement 日期== price_movement 日期。有人可以就是否有办法做到这一点提出建议吗?

回答by Siva

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

Go through this linkit has detailed explanation of how to use ActiveRecord

通过此链接,它详细说明了如何使用ActiveRecord