3

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:

data model

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?

ringe
  • 812
  • 6
  • 14

1 Answers1

3

To override the default generated query in a Rails 4 has_many relationship I did the following:

has_many :discounts,
         -> (cu) { unscope(:where).for_customer(cu) }

The method to look up and make use of is unscope

ringe
  • 812
  • 6
  • 14