简体   繁体   English

如何在Ruby on Rails中编写连接条件?

[英]how to write a join condition in Ruby on Rails?

what I'm trying to do is to write something like the next query: 我想要做的是编写类似于下一个查询的内容:

SELECT *
FROM Customers c
LEFT JOIN CustomerAccounts ca
    ON ca.CustomerID = c.CustomerID
    AND c.State = 'NY'

Notice that I'm not using any WHERE clause, but I need to my JOIN have a condition. 注意,我没有使用任何WHERE子句,但是我需要对JOIN有一个条件。 I cannot make it work in Ruby on Rails. 我无法使其在Ruby on Rails中工作。

Can you help me out? 你能帮我吗?

You can join the tables with LEFT JOIN . 您可以使用LEFT JOIN表。 Just pass the join condition in joins and you will get the expected result 只要在joins通过joins条件,您将获得预期的结果

Customer.joins("LEFT JOIN CustomerAccounts
                ON CustomerAccounts.CustomerID = Customers.CustomerID
                AND Customers.State = 'NY'")

#=> SELECT * FROM Customers LEFT JOIN CustomerAccounts ON CustomerAccounts.CustomerID = Customers.CustomerID AND Customers.State = 'NY'

Note: just .joins() does INNER JOIN so you need to specify the join with condition 注意:只有.joins()可以进行INNER JOIN因此您需要使用条件指定INNER JOIN

Your SQL code, translated to activerecord, would look as follows (using joins ): 转换为activerecord的SQL代码如下所示(使用joins ):

Customer.where(state: 'NY').joins(:customer_accounts)

The code assumes, you have the association set up: 代码假定,您已建立关联:

class Customer
  has_many :customer_accounts
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM