Reputation: 188
I am trying to display the the first image from the albums table that belongs to the a post
class Post < ActiveRecord::Base
has_many :albums, dependent: :destroy
end
class Album < ActiveRecord::Base
belongs_to :post
end
and in the post index I wanted to display the one of the images that belongs to a post in the post/index page
class PostsController < ApplicationController
before_action :signed_in_user, only: [ :new, :create, :edit, :update, :destroy]
before_action :set_post, only: [:edit, :update, :destroy] #:show,
def index
@albums = Album.all
@posts = Post.all
end
def show
@post = Post.find(params[:id])
@user = @post.user(params[:id])
@album = Album.new
@album.post_id = @post.id
end
def new
@post = Post.new
end
def create
if current_user
@post = current_user.posts.build(post_params)
if @post.save
redirect_to @post, notice: 'Post was successfully created.'
else
render action: 'new'
end
end
end
end
this is the albums controller
class AlbumsController < ApplicationController
def create
@album = Album.new(album_params)
@album.post_id = params[:post_id]
@album.save
redirect_to post_path(@album.post), notice: 'photo added successfully'
end
end
below is the views/posts/index.html.erb page
<% @posts.each do |post| %>
<%= post.title %>
<% post.albums.each do |album| %>
<%= image_tag album.image.url(:thumb) %>
<% end %>
<% end %>
what do I need to do so that I can display the first image in a post?
Upvotes: 1
Views: 4019
Reputation: 1049
What you probably need to do is loop the relation to display the image:
<% @posts.each do |post| %>
<%= post.title %>
<% post.albums.each do |album| %>
<%= image_tag album.image_url %>
<% end %>
<% end %>
If you'd like to only display one image (the first one) this could be done.
<% @posts.each do |post| %>
<%= post.title %>
<%= image_tag post.albums.first.image_url %>
<% end %>
Upvotes: 2
Reputation: 2504
To display the first image you can use
<%= image_tag post.albums.first.image_url %>
Upvotes: 0