ActiveRecord and :include


#1

here is my model

class ProductLocation < ActiveRecord::Base
belongs_to :property
has_many :product_location_mappings
end

I want to load product_locations along with
referenced :product_location_mappings and return a deep model.

@product_locations = ProductLocation.find_all_by_property_id

(property_id, :include => [:property, :product_location_mappings])

however result does not include :product_location_mappings…
I am using rails 2.3.2, not sure what to do…


#2

slava wrote:

here is my model

class ProductLocation < ActiveRecord::Base
belongs_to :property
has_many :product_location_mappings

Tip: Model names shouldn’t be redundant with their navigation. Just call
it
Mappings. An even better name would reveal the intent of the model…

I am using rails 2.3.2, not sure what to do…
Show a unit test that includes all your models linked together, per
their yml
fixture files. Then show that find() statement locating your target
record.

If the code still does not work, gem install assert2
assert_efficient_sql,
require ‘assert_efficient_sql’, and wrap this around your test:

inspect_sql :verbose => true do
product_locations = ProductLocation.find_all_by_property_id
(property_id, :include => [:property,
:product_location_mappings])
end

BTW you might also have read your log/test.log, but inspecting your code
is what
tests are for…

You will get a big blob of JOIN statements. Inspect them to see if they
make
sense, and run them in your database directly to see what they do.

But, in general, your code looks like the :include directives I have
written, so
I don’t see any specific problem with it. That’s why the shotgun of
recommendations.


Phlip


#3

thanks,
I ended up doing this.

  format.json  { render :json => @product_locations.to_json

(:include => :product_location_mappings)}