# Extra Model Attributes from DB

**URL:** <https://www.ruby-forum.com/t/extra-model-attributes-from-db/105745>\
**Category:** Rails\
**Created:** [June 2, 2007, 1:31am UTC](https://www.ruby-forum.com/t/extra-model-attributes-from-db/105745 "2007-06-02T01:31:32Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![PeteSalty](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/bc79bd/32.png) [@PeteSalty](https://www.ruby-forum.com/u/PeteSalty)\
**Post date:** [June 2, 2007, 1:31am UTC](https://www.ruby-forum.com/t/extra-model-attributes-from-db/105745/1 "2007-06-02T01:31:32Z")

</div>

We have two models, Articles and Votes; it’s the typical situation;  
users can vote on articles so the models look something like this:

class Article \< ActiveRecord::Base

has\_many :votes

end

class Vote \< ActiveRecord::Base

belongs\_to :user  
belongs\_to :article

end

(user isn’t listed here because it’s not important but you get the  
idea).

What we want to do is actually get back the number of votes with the  
article

The SQL for this is pretty straight forward and looks like:

```
SELECT articles.*, COUNT(votes.id) AS vote_count FROM
  articles INNER JOIN votes ON articles.id = votes.article_id
GROUP BY articles.id

```

We’d like to be able to then do something like

Article.find(:all, :order =\> “vote\_count DESC”)

and

\<%= Article.find(125).vote\_count %\>

problem is, we can’t work out if it’s even possible in Rails to make  
the Article model use this SQL, or if there’s another solution we’re  
overlooking.  
Does anyone know if it can be done or could point us in the right  
direction?

Pete
