I started rails issue #7121, but I think this needs some discussion as it's 
not just a simple "bug". I might take a stab at it myself, but I'd like to 
get a blessing or consensus on this:

Given a relation:

1. When .group is added for conditions, this forces .count into returning a 
grouped count instead of a flat numeric count.

2. When .select("virtual_col") and .order("virtual_col") are used, .count 
fails with a SQL error because the .select is rewritten for COUNT(*) but 
the .order is still there pointing to a non-existent column.

I found a solution for these by wrapping the relation in a subquery. This 
isolates the relation so calculate doesn't see its group_values and 
select_values and can't mess them up:

    def self.wrapped
      inner_scope = self.all # 3.2: use self.scoped
      self.unscoped do
        from(inner_scope.as(table_name))
      end
    end

Currently I use this by manually wrapping my relation before before calling 
.count on it: relation.wrapped.count

Is there any reason why Relation#calculate shouldn't work this way by 
default? For grouped counts, here's what I suggest:

1. count() on a relation that uses group_values should just return a 
numeric count of records, not a hash.

2. grouped counts must be done explicitly: .count(group: "column") or 
.count_by("column") should return a hash.

Currently, finder methods on calculate are deprecated so using 
.count(group: "column") logs a warning, but with the wrapped method it all 
works.

How to proceed?

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/rubyonrails-core/-/FfZEE-GWAw8J.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.

Reply via email to