2015-04-21 44 views
0

我正在使用Rails 4构建博客。每篇博文都有图片,标题和文字。我可以上传一张图片,当我查看posts /:id页面时,看到图片在那里,但后来当我回到同一页面时图片消失了。我正在使用回形针4的回形针宝石。上传的图像显示为保存,然后消失

我的图片是否以某种方式与会话绑定?它不是真的保存到数据库吗?以下是部署项目的链接,但未显示图像: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> 
+3

您可能需要设置AWS S3帐户,请检查此https://devcenter.heroku.com/articles/paperclip-s3 – Cyzanfar

+2

Seconding @Cyzanfar,有这个确切的问题,并使用S3来解决。 –

回答

3

这应该工作单台机器上的罚款。然而,使用heroku您的应用程序应该是一个12因子应用程序。在这种情况下,您不应该使用文件系统,而应该使用额外的服务来存储文件。这是因为heroku上的应用程序代码分布在多个物理硬件实例中,并且您永远不知道哪个实际节点将对https://vinna.herokuapp.com/posts/1作出响应。所以你的第一个看到某个特定节点上的图像,然后你的负载平衡到其他没有存储的其他节点上。

请参阅The Twelve-Factor-App的第四点。

相关问题