简体   繁体   中英

display images in rails

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?

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 %>

要显示第一张图像,您可以使用

<%= image_tag post.albums.first.image_url %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM