I’ve been playing around with special relationships (specifying the
select, etc) on my models and trying to get Rails to return the
results of database computations as part of an association. I’ve got
one model representing an object and another model representing
statistics about that object on per day basis. That main Event object
has many Stats but it also has one Summary (of those Stats).
Unfortunately, Rails won’t allow me to have a has one association with
computed columns (sums in my case) since it will not allow the use of
the group by clause without which Rails can’t connect the returned
stats to the event since the event_id column is null. I’ve gotten
around this by using a has_many association for the stats even though
I’m grouping on the foreign key and will only ever have one record at
most. This creates some really “hacky-looking” code since I have to
read the first element of the returned array everywhere to read the
summary stats. I went digging through the Rails source to take a look
at why this might be prevented and I’ve come up with two thoughts:
Rails should allow use of :group for a has_one association for
specific use cases such as this one and let the programmer decide how
it works. The fix is as simple as adding it to the
valid_keys_for_has_one_association in associations.rb. However, this
lead me to a second thought…
In a has_one association it seems like it would never be
detrimental to use a group by clause on the foreign key as this would
always return one or fewer results for the parent table. This relates
to the comment at association_preload.rb:148 (in 2.3.3) which states
that there is no way to ask the database for one row per distinct
foo_id (which is what group by would do, at least in MySQL).
Am I missing something or is this something that ought to be patched?
Thanks for the input and help!