# Association to return only the first of an associated list

**URL:** <https://www.ruby-forum.com/t/association-to-return-only-the-first-of-an-associated-list/155120>\
**Category:** Rails\
**Created:** [December 8, 2008, 11:59am UTC](https://www.ruby-forum.com/t/association-to-return-only-the-first-of-an-associated-list/155120 "2008-12-08T11:59:17Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [December 8, 2008, 11:59am UTC](https://www.ruby-forum.com/t/association-to-return-only-the-first-of-an-associated-list/155120/1 "2008-12-08T11:59:17Z")

</div>

A little background: in our schema, Resource has\_many :assets, through a  
join table called items.

Whenever we show a resource, we also show a thumbnail for its first  
associated asset. Currently, this means that we’re doing a lot of sql  
action in the view: for example, a partial like this might be repeated  
100 times:

…  
\<% asset = resource.assets.first %\>  
\<%= image\_tag asset.name, asset.path %\>  
…

Obviously doing loads of little queries in the view isn’t good: what  
i’d like to do is somehow eager-load that first asset with the include  
option. We tried making a method called ‘primary\_asset’ which returns  
the first asset for a resource, but that can’t be "include"d: i think  
that in order to include it i need to set it up as an association.  
Which leads me to my actual question: how do i set up a has\_one  
association to return only the first asset from the collection of  
associated assets?

has\_one doesn’t seem to have an ‘sql’ option, otherwise i’d just do  
something like

has\_one :primary\_asset, :class\_name =\> “Asset”, :sql =\> “SELECT  
assets.\* FROM assets INNER JOIN items ON assets.id = items.asset\_id  
WHERE ((items.resource\_id = #{id})) ORDER BY position LIMIT 1”

Can anyone see how i can set this up? I’m using rails 2.0.2.

thanks, max

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [December 8, 2008, 7:20pm UTC](https://www.ruby-forum.com/t/association-to-return-only-the-first-of-an-associated-list/155120/2 "2008-12-08T19:20:38Z")

</div>

Have you tried

has\_one :primary\_asset, :class\_name=\>“Asset”, :order=\>“position”

On Dec 8, 4:59 am, Max W. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
