2015-04-21 87 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的第四點。

相關問題