【问题标题】:Uploaded images appear to save, then disappear later上传的图像似乎保存,然后消失
【发布时间】:2015-04-21 18:45:33
【问题描述】:

我正在使用 Rails 4 构建博客。每篇博文都有图片、标题和文字。我可以上传一张图片,当我查看 posts/:id 页面时看到图片就在那里,但后来当我回到同一页面时,图片就不见了。我正在为 rails 4 使用 Paperclip gem。

我的图像是否以某种方式与会话相关联?它不是真的保存到数据库吗?这是已部署项目的链接,其中未显示图像:https://vinna.herokuapp.com/posts/1

我还在学习中,非常感谢任何信息!

这是我的控制器:

class PostsController < ApplicationController
def index
    @posts = Post.all
end

def new
    @post = Post.new
end

def create
    @post = Post.new(post_params)

    if @post.save
        redirect_to @post
    else
        render 'new'
    end
end

def show
    @post = Post.find(params[:id])
end

def edit
    @post = Post.find(params[:id])
end

def update
    @post = Post.find(params[:id])

    if @post.update(post_params)
        redirect_to @post
    else
        render 'edit'
    end
end

def destroy
    @post = Post.find(params[:id])
    @post.destroy

    redirect_to posts_path
end

private
    def post_params
        params.require(:post).permit(:image, :title, :text)
    end
end

我的模特:

class Post < ActiveRecord::Base
has_many :comments
has_attached_file :image, styles: { small: "100x100", med: "200x200", large: "600x600"}

validates :title, presence: true,
                                    length: { minimum: 2 }

validates :text, presence: true,
                                    length: { minimum: 2 }

validates_attachment_presence :image
validates_attachment_size :image, :less_than => 5.megabytes
validates_attachment_content_type :image, :content_type => ['image/jpeg', 'image/png']
end

我的迁移:

class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
  t.string :title
  t.text :text

  t.timestamps null: false
end
end
end

并添加回形针:

class AddPaperclipToPost < ActiveRecord::Migration
def change
add_attachment :posts, :image
end
end

我的部分观点来自帖子/:id

    <p class="blog-photo_large"><%= link_to image_tag(@post.image.url(:large)), @post.image.url %></p>

【问题讨论】:

标签: ruby-on-rails image ruby-on-rails-4 paperclip


【解决方案1】:

这在单机上应该可以正常工作。但是,使用 heroku,您的应用程序应该是 12 因素应用程序。在这种情况下,您不应该使用文件系统,而是使用用于存储文件的附加服务。这是因为 heroku 上的应用程序代码分布在多个物理硬件实例上,您永远不知道哪个实际节点将响应 https://vinna.herokuapp.com/posts/1。因此,您首先会在某个特定节点上看到图像,然后将您的图像负载平衡到其他没有存储它的节点上。

参见The Twelve-Factor-App 的第四点。

【讨论】:

    猜你喜欢
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 2012-07-31
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    相关资源
    最近更新 更多