Feng Ding
Feng Ding

Reputation: 17

ruby on rails display one image from many images

I the following Post and Attachment models:

class Post < ActiveRecord::Base
  has_many :attachments, dependent: :destroy    
end

class Attachment < ActiveRecord::Base
  belongs_to :post
end

In my page I can only do like this:

<% post.attachments.each do |p| %>
  <%= image_tag p.image_url.to_s %>
<% end %>

This will show every image (every attachments) for a post.

If I only want to display the first image (when the attachment.id is minimum I guess) for a post. What should I do?

Upvotes: 1

Views: 396

Answers (2)

miahabdu
miahabdu

Reputation: 614

If you're only trying to display the first attachment of a post you can do this:

<%= image_tag post.attachments.first.try(:image_url).to_s %>

instead of iterating over all the attachments.

Upvotes: 1

rony36
rony36

Reputation: 3339

this will show the first attachment of the post:

<%= image_tag post.attachments.first.image_url.to_s unless post.attachments.blank? %>

Upvotes: 1

Related Questions