Forum: Ruby on Rails find :all in subclass within STI finds parents instead

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Patrick (Guest)
on 2009-05-11 12:29
(Received via mailing list)
All,

I am relative new to Rails and struggle with following STI issue:

A parent class "Reading" has many subclasses "ElectricityReading",
"GasReading", ...

I wrote a method in the Reading class to update calculated columns in
each record, the logic goes like this:

1. Find first record

first = find(:first, :conditions =>  ["unit_id = ?", unit_id], :order
=> "date asc" )
# get values of some columns and store in local variables

2. Find all records, perform the calculations and store in calculated
fields

find(:all, :conditions =>  ["unit_id = ?", unit_id], :order => "date
asc" ).each do |r|
# get column values of r, calculate and save

3. Controller calls the method after each create or entry
ElectricityReading.calculate(unit_id)


The problem:

Instead of

SELECT * FROM "readings" WHERE (unit_id = 1) AND ( ("readings"."type"
= 'ElectricityReading' ) Limit 1
SELECT * FROM "readings" WHERE (unit_id = 1) AND ( ("readings"."type"
= 'ElectricityReading' )

I get

SELECT * FROM "readings" WHERE ("readings"."id" = '10') LIMIT 1
SELECT * FROM "readings" WHERE ("readings"."id" = '10')

So the calculations are performed on all Reading objects rather than
only the ElectricityReading object.

The funny thing is that it seems to work as expected in the console,
but fails as above using the built in server.

Is this a bug in STI?  Would it be solved by using a different type of
inheritance?
Mukund (Guest)
on 2009-05-11 16:48
(Received via mailing list)
Check the lines in the log above SELECT * FROM "readings" WHERE
("readings"."id" = '10') LIMIT 1

Rails tends to break up long SQL statements into smaller ones.   More
information about your code snippet is required to make any guesses.
Have a look at
http://api.rubyonrails.org/classes/ActiveRecord/As...
This topic is locked and can not be replied to.