Hmmmm..sounds so simple but

Hey,
I’m having a little problem…
I’m trying to display a list of say “entries”
Each entry has_many images but in the main listing I want to only
display 1 image against each post… how do I do that!!! Sounds so simple
but can’t work it out…

here’s the code:

CONTROLLER

def index
@users = User.find(:all, :select =>“screen_name, id”)
@projects = Project.find(:all, :select =>“id, title, permalink,
category_id, user_id”)
end

VIEW

<% for project in @projects %>
<% for image in project.images %>
<%= link_to(image_tag(image.public_filename(:mini)), :action =>
project.user.screen_name, :id => project) %>
<% end %>

<%= link_to h(project.title), :action => project.user.screen_name, :id
=> project %><%= project.category.category_name %>
<% end %>

So If I have only one image per project, this is fine but (obviously) if
I have multiple images on one project, they all come up because of the
for loop…

Please please please someone help, I’m going mad :S

thanks
Oli

kick out the loop and use project.images.first instead

On 03 Apr 2008, at 16:53, Olivier B. wrote:

<% for project in @projects %>
So If I have only one image per project, this is fine but
(obviously) if
I have multiple images on one project, they all come up because of the
for loop…

Please please please someone help, I’m going mad :S

Although you could use Thorsten’s images.first technique, you’re
loading all images while you only need one. The method below could be
more performant and you can change the main_image logic if necessary
in your model, where it should belong.

MODEL

class Project
has_one :main_image, :class_name => “Image”, :foreign_key =>
“project_id”
# leave all the rest you have here too, such as the one-to-many
relationship, for when you need all the images

end

CONTROLLER

def index
@users = User.find(:all, :select =>“screen_name, id”)
# Eager load the main_image, it’s going to be more performant and
just lose the select
@projects = Project.find(:all, :include => [:main_image])
end

VIEW

<% for project in @projects %>
<%=
link_to(image_tag(project.main_image.public_filename(:mini)), :action =>
project.user.screen_name, :id => project) %>

<%= link_to h(project.title), :action => project.user.screen_name, :id
=> project %><%= project.category.category_name %>
<% end %>

Best regards

Peter De Berdt

Peter

works a treat… thank you ever so much for your help… It’s my first
time here and I ma very VERY impressed.

Thanks again
Olivier