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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With