Rails 4 lets you scope a has_many
relationship like so:
class Customer < ActiveRecord::Base
has_many :orders, -> { where processed: true }
end
So anytime you do customer.orders
you only get processed orders.
But what if I need to make the where
condition dynamic? How can I pass an argument to the scope lambda?
For instance, I only want orders to show up for the account the customer is currently logged into in a multi-tenant environment.
Here's what I've got:
class Customer < ActiveRecord::Base
has_many :orders, (account) { where(:account_id => account.id) }
end
But how, in my controller or view, do I pass the right account? With the code above in place when I do:
customers.orders
I get all orders for account with an id of 1, seemingly arbitrarily.