Optional Include Relationship


#1

I did some searches in the mailing list and on the web but I can’t
seem to find the answer to this, but it’s pretty much a noob question.

I have a Product object

class Product < ActiveRecord::Base
has_many :product_identifications
has_one :product_identification_item_number
has_one :product_identification_product_code
end

the product_identifications is using STI to have the two optional
product identifiers Item Number and Product Code.

I would like to use this on a listing screen but use :include to keep
it at only one query, however when i add “:include
=> :product_identification_item_number” i only get back records where
an Item Number exists for the product. I did try including the base
product_identifications, which doesn’t limit the results but wouldn’t
be the cleanest way for my presentation.

Any help would be greatly appreciated,
Dave


#2

it at only one query, however when i add “:include
=> :product_identification_item_number”

@products.find(:all)

for product in @products
product.product_identification_item_number


#3

Anthony G. wrote:

it at only one query, however when i add “:include
=> :product_identification_item_number”

@products.find(:all, :include => :product_identification_item_number)

for product in @products
product.product_identification_item_number

should work

Whats is the sql being generated in the development log ?

_Tony


#4

Thinking about this a little more, I’m guessing this only affects
models using STI, as typically there wouldn’t be the additional WHERE
statement. Is this possibly addressed in EdgeRails?

Dave


#5

Hi Antony,

Here is the generated SQL:

SELECT product_identifications.id AS t1_r0,
product_identifications.product_id AS t1_r1, products.id AS
t0_r0, product_identifications.type AS t1_r2, products.name AS
t0_r1, product_identifications.id_value AS t1_r3 FROM products LEFT
OUTER JOIN product_identifications ON
product_identifications.product_id = products.id WHERE
(product_identifications.type = ‘ProductIdentificationItemNumber’ )
LIMIT 0, 10e

It definitely will only return products that have an associated
product_identification_item_number, if the “WHERE
(product_identifications.type =
‘ProductIdentificationItemNumber’ )” was located in the join it would
make it optional.

Thanks,
Dave


#6

Dave,

Check out http://wiki.rubyonrails.org/rails/pages/Allow+Multiple
+Associations+Same+Table+Plugin

With that in place, Rails 1.0 will correctly generate the conditions
on the JOIN.

Edge Rails doesn’t yet solve the same problems as this plugin, but it
looks like it’s moving closer to doing so.

Cheers,

Pete Y.