Rails4:如何使用关联显示上传的文件?

时间:2014-07-06 08:57:38

标签: ruby-on-rails ruby-on-rails-4 carrierwave

我可以使用carrierwave上传文件并将文件名保存在数据库中。我想使用关联在另一个页面上显示文件图像。

(Althogh我问过question与此相关的内容,另外一条评论是无法禁止的。所以我将此作为一个新问题重新输入。)

user.rb

class User < ActiveRecord::Base
  has_many :articles, dependent: :destroy
    .
    .
end

article.rb

class Article < ActiveRecord::Base
    .
    .
    belongs_to :user
    has_many :photos, dependent: :destroy
    accepts_nested_attributes_for :photos
    .
    .
end

photo.rb

class Photo < ActiveRecord::Base
    belongs_to :article
    mount_uploader :image, ImageUploader
    validates :image, presence: true
    #validates :article_id, presence: true
end

.schema文章

CREATE TABLE "articles" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
"content" varchar(255), 
"user_id" integer, 
"created_at" datetime, 
"updated_at" datetime,);

.schema照片

CREATE TABLE "photos" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
"article_id" integer, 
"image" varchar(255), 
"created_at" datetime, 
"updated_at" datetime);

users_controller.rb

class UsersController < ApplicationController
    .
    .   
  def show
    @user = User.find(params[:id])
    @articles = @user.articles.paginate(page: params[:page])
  end
    .
    .
end

articles_controller.rb

class ArticlesController < ApplicationController
    .
    .
  def new
    @article = Article.new
    @article.photos.build
    .
    .
  end

  def create
    @article = current_user.articles.build(article_params)
    .
    .
  end

  def edit
    @article = Article.find(params[:id])
  end

  def update
    @article = Article.find(params[:id])
    if @article.update(article_params)
      redirect_to current_user
    else
      render 'edit'
    end
  end
    .
    .
  private

    def article_params
      params.require(:article).permit(:content, photos_attributes: [:id, :article_id, :image])
    end
    .
    .
end

用户\ show.html.erb

    .
    .
<div class="row">
        <%= render @articles %>
</div>
    .
    .

articles \ _article.html.erb

我想在此处显示上传的图片

<li>
    .
    .
  #Please let me know how to display image here...
  <span class="content"><%= article.content %></span>
    .
    .
</li>

1 个答案:

答案 0 :(得分:0)

我不明白为什么会出现这样的问题。显然你正在使用Carrierwave上传图像。如果您阅读其文档,您会发现获取图像URL并将其显示在页面上非常简单。您需要image_tag来执行此操作。

要在articles\_article.html.erb中显示图像,您可以执行以下操作:

<li>
    .
    .
  #Please let me know how to display image here...
  <span class="content"><%= article.content %></span>

  <% article.photos.each do |photo| %>
    <span class="image"><%= image_tag(photo.image_url) if photo.image? %></span>
  <% end %>
    .
    .
</li>