Forum: Ruby on Rails Association to return only the first of an associated list

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
73c04e9ef9ca435c5b19a2e765ae6d20?d=identicon&s=25 Max Williams (max-williams)
on 2008-12-08 11:59
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.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 = 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
82e01981fb1270c0a54c544f9af342c5?d=identicon&s=25 JDevine (Guest)
on 2008-12-08 19:20
(Received via mailing list)
Have you tried

has_one :primary_asset, :class_name=>"Asset", :order=>"position"

On Dec 8, 4:59 am, Max Williams <>
This topic is locked and can not be replied to.