views:

30

answers:

1

I am trying to only fetch the first record in my table for display. I am creating a site where a user can upload multiple images and attach to a post but I only want to display the first image view for each post.

For further clarification posts belong_to projects. So when you are on the projects show page you see multiple posts. In this view I only want to display the first image for each post. Is there a way to do this in the view without affecting the controller (as later I want to allow users to browse all photos through the addition of a lightbox). Here is my /views/posts/_post.html.erb code:

<% div_for post do %>

    <% post.photos.each do | photo | %>

        <%= image_tag(photo.data.url(:large), :alt => '') %>
        <%= photo.description %>
    <% end unless post.photos.first.new_record? rescue nil %>

        <%= link_to h(post.link_title), post.link %>
        <%=  h(post.description) %>

        <%= link_to 'Manage this post', edit_post_path(post) %> 

<% end %>

UPDATE: I am using a photos model to attach multiple photos to each post and using paperclip here.

A: 

either of these should work?

post.photos.find(:first)

or 

post.photos.first

EDIT: I think the revised code would look like this?

<% div_for post do %>
    <% photo = post.photos.first %>

    <%= image_tag(photo.data.url(:large), :alt => '') %>
    <%= photo.description %>

    <%= link_to h(post.link_title), post.link %>
    <%=  h(post.description) %>

    <%= link_to 'Manage this post', edit_post_path(post) %> 
<% end %>
house9
do I have to keep the '...do |photo|...' having trouble getting that to work. Can you include the full syntax as I am new to ruby and rails.
bgadoci
FYI, when I do `<% post.photos.first do | photo | %>` the images don't display at all. See my edit that the photos are in a photos table and appended to post through a photos model, no controller for photos (or view).
bgadoci
first will return a single object where photos is returning an array, so no you do not need the do block, will update
house9
Worked perfectly. Thank you very much.
bgadoci