Ruby on Rails: How to do a query on a table having two foreign key references with ActiveRecord

activerecord, ruby-on-rails

Solution

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

Problem

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.

Original source