views:

715

answers:

1

Hi there,

I'm trying to create an association between two models using join conditions rather than a foreign key. Does anyone know if this is possible?

For example I want to join products to pricing points. A product has a price and a pricing point has a minimum and maximum amount and a name. Eg. Min = 0, Max = 20, Name = Less than $20. The association between the product is on the price and the min and max.

SELECT *
FROM products
INNER JOIN pricing_points
ON pricing_points.minimum < products.price AND pricing_points.maximum >= products.price

Does this make sense? So I want something like this in my model:

class Product < ActiveRecord::Base

  belongs_to :pricing_point, :join => "INNER JOIN pricing_points ON pricing_points.minimum < products.price AND pricing_points.maximum >= products.price"

  ...

end

Thanks in advance for your help,

Caps

A: 

You can't really define that type of relationship using ActiveRecord. AR provides the :conditions option but it only applies to the WHERE portion of your query, it would still attempt to join on pricing_point_id = pricing_point.id.

You'll want to do the following:

Products.find :all, :joins => "INNER JOIN pricing_points \
    ON pricing_points.minimum < products.price \
    AND pricing_points.maximum >= products.price"

You can move this to a method in your Products class for convenience.

Another option is to use raw SQL for this.

hobodave
Yeah I thought that may be the case. I wanted to map the association because I'm using Thinking Sphinx and I would like to use the association in my search index. Thanks for your help though.
Caps