简体   繁体   中英

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? 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.

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.

This has the advantage of being only one SQL call.

The rails query guide is very useful - 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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