[英]Ruby on Rails: How to do a query on a table having two foreign key references with ActiveRecord
I have three models: Customer, Bank and Account. 我有三种模式:客户,银行和账户。 each customer can have many accounts, so does a bank. 每个客户都可以拥有多个账户,银行也是如此。
class Customer < ActiveRecord::Base
has_many :Accounts
class Bank < ActiveRecord::Base
has_many :Accounts
Account < ActiveRecord::Base
belongs_to :Customer, :foreign_key => 'customerID'
belongs_to :Bank, :foreign_key => 'bankID'
If I want to find all accounts for customer Jack, I can do 如果我想找到客户杰克的所有账户,我可以做到
Customer.find_by_name('jack').Accounts
If I want to find all accounts for Citi bank, then I can do query like 如果我想查找花旗银行的所有账户,那么我可以查询
Bank.find_by_name('Citi').Accounts
My question is how can I find the account for Customer Jack which belongs to the Citi bank with ActiveRecord? 我的问题是如何通过ActiveRecord找到属于Citi银行的Customer Jack帐户? There is some way to explicitly generate a SQL statement but I wonder how can I do similar queries for other models having the same relationship in a generic way. 有一些方法可以显式生成SQL语句,但我想知道如何以通用方式对具有相同关系的其他模型执行类似的查询。
accounts = Account.joins(:bank, :customer)
.where( banks: { name: "Citi" }, customers: { name: "Jack" } )
I think I've got the plurals bank/banks, customer/customers the right way round. 我想我的复数银行/银行,客户/客户是正确的。 If it doesn't work first time, try it in the console - build it up by stages, the joins first, then the where bit. 如果它第一次不起作用,请在控制台中尝试 - 按阶段构建,首先连接,然后在where位。
This has the advantage of being only one SQL call. 这样做的好处是只能进行一次SQL调用。
The rails query guide is very useful - http://guides.rubyonrails.org/active_record_querying.html rails查询指南非常有用 - http://guides.rubyonrails.org/active_record_querying.html
bank = Bank.find_by_name('City')
accounts = Customer.find_by_name('jack').accounts.where(:bank_id => bank.id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.