Tuesday, May 4, 2010

[Rails] AR: dynamic accessors don't always work?

This is curious. Consider 'record' below, derived from an SQL query.
Notice that record.station_id returns the station id properly, but
record.start_time returns nil. What's the difference? (FWIW, I *can*
access the start_time via the construct record[:start_time]).

This took me a while to track down, so I need to know: what's the
difference between the two fields? And - more importantly - what part of
the documentation explains what's going on?

>> record
=> #<WeatherObservation precipitation_m: 0.0>

>> record.station_id
=> "KCAMILLV8" # got the station id

>> record.start_time
=> nil # where's the start time?

>> record[:start_time]
=> "2007-01-01 00:00:00" # ah - there it is! but wtf?

>> record.attributes
=> {"end_time"=>"2007-01-02 00:00:00", "precipitation_m"=>0.0,
"start_time"=>"2007-01-01 00:00:00", "station_id"=>"KCAMILLV8",
"temperature_c"=>"8.88889"}

I'm not sure this is germane to the problem, but here's the SQL query
that produced the record. NOTE: neither "station_id" nor "start_time"
are 'native' slots in the WeatherObservation class:

SELECT st.datetime AS start_time,
et.datetime AS end_time,
ws.station_id AS station_id,
wo.temperature_avg_c AS temperature_c,
wo.precipitation_m AS precipitation_m
FROM weather_observations AS wo
INNER JOIN weather_stations AS ws ON wo.weather_station_id = ws.id
INNER JOIN time_dimensions AS st ON wo.start_time_id = st.id
INNER JOIN time_dimensions AS et ON wo.end_time_id = et.id
WHERE ws.id IN (#{station_ids}) AND
st.datetime BETWEEN \'#{start_date}\' and \'#{end_date}\' AND
et.datetime BETWEEN \'#{start_date}\' and \'#{end_date}\'

... all wrapped up in WeatherObservation.find_by_sql(), of course.
--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment