# Find\_by\_sql Doesn't Return Attributes?

**URL:** <https://www.ruby-forum.com/t/find-by-sql-doesnt-return-attributes/141236>\
**Category:** Rails\
**Created:** [June 23, 2008, 10:36pm UTC](https://www.ruby-forum.com/t/find-by-sql-doesnt-return-attributes/141236 "2008-06-23T22:36:37Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![karlshea](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/58956e/32.png) [@karlshea](https://www.ruby-forum.com/u/karlshea)\
**Post date:** [June 23, 2008, 10:36pm UTC](https://www.ruby-forum.com/t/find-by-sql-doesnt-return-attributes/141236/1 "2008-06-23T22:36:37Z")

</div>

My find\_by\_sql is not returning attributes of the calling model class.

Thermo.find\_by\_sql(“SELECT COUNT(\*) FROM thermo WHERE thermo\_loc =  
‘back’ GROUP BY DAYOFWEEK(time\_on) ASC”)

# ==\> [#, #, #, #, #,

#, #]

The sql is fine and when I checked it in a mysql console, it returns  
the day of the week and count.

Any ideas why Rails (2.1 btw) is not bringing in the resulting columns  
into Thermo model attributes?

PS - if there is a way to rewrite this kind of query into AR, that  
would be great too.

Karl

---

<div class="post-metadata">

**Author:** ![karlshea](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/58956e/32.png) [@karlshea](https://www.ruby-forum.com/u/karlshea)\
**Post date:** [June 24, 2008, 3:03am UTC](https://www.ruby-forum.com/t/find-by-sql-doesnt-return-attributes/141236/2 "2008-06-24T03:03:35Z")

</div>

Karl S. wrote:

> My find\_by\_sql is not returning attributes of the calling model class.
> 
> Thermo.find\_by\_sql(“SELECT COUNT(\*) FROM thermo WHERE thermo\_loc =  
> ‘back’ GROUP BY DAYOFWEEK(time\_on) ASC”)
> 
> # ==\> [#, #, #, #, #,
> 
> #, #]
> 
> The sql is fine and when I checked it in a mysql console, it returns  
> the day of the week and count.
> 
> Any ideas why Rails (2.1 btw) is not bringing in the resulting columns  
> into Thermo model attributes?
> 
> PS - if there is a way to rewrite this kind of query into AR, that  
> would be great too.
> 
> Karl

Hi Karl,

I’m just going to take a blind stab. Try including the group column in  
the select statement and give the count an alias. Something like

select dayofweek(time\_on) as day\_of\_week, count(\*) as day\_count  
from thermo  
where thermo\_loc = ‘back’  
group by dayofweek(time\_on)

As for how to write it in AR, you could probably do it with :select and  
:group, but I haven’t tried.

Peace,  
Phillip
