I need to override the defailt ActiveRecord generated SQL query in a has_many relationship. While finder_sql is deprecated in Rails 4.
In a given legacy application there are multiple relationships between customers and their available discounts. It looks like this:
A Rails 4 scope on discounts to fetch all available discounts for a given customer:
scope :for_customer, lambda { |customer|
where("CustomerNo = '#{customer.CustomerNo}'
OR DiscountGrpCustNo = '#{customer.DiscountGrpCustNo}'
OR PriceListNo = '#{customer.PriceListNo}'")
}
So I wanted to use this scope to define the has_many on the customer. I found an explanation for using variables on a has_many in a different question here: https://stackoverflow.com/a/2462397/1062276
So I tried:
has_many :discounts,
-> (customer) { for_customer(customer) }
Which resulted in Invalid column name 'customer_id'
due to the following:
> customer.discounts.to_sql
SELECT [KuraasAS].[DiscountAgreementCustomer].* FROM [KuraasAS].[DiscountAgreementCustomer] WHERE [KuraasAS].[DiscountAgreementCustomer].[customer_id] = 12345 AND (CustomerNo = '12345'
OR DiscountGrpCustNo = '5'
OR PriceListNo = '3')
The customer_id column is Rails's assumption. How can I take this out of the query?