2013-03-31 28 views
0

我正在设置一个基本的博客,其中包含可选的图片上传文章。图像正在正确上传并转到正确的目录。然而,当我去查看它加载默认的图像:Rails +回形针没有给视图中的图片url

photos/original/missing.png 

这里是模型

class Post < ActiveRecord::Base 
    attr_accessible :body, :date, :feature, :poster, :title, :photo 

    has_attached_file :photo, :styles => { :medium => "300x300>", :thumb => "100x100>" }, 
        :url => "/assets/posts/:id/:style/:basename.:extension", 
        :path => ":rails_root/public/assets/posts/:id/:style/:basename.:extension" 

    attr_accessor :photo_file_name 
    attr_accessor :photo_content_type 
    attr_accessor :photo_file_size 
    attr_accessor :photo_updated_at 
end 

并在视图:

<%= image_tag @post.photo.url %> 

例如,我上传的图像与帖子,并将其上传到:

rails_root/public/assets/posts/5/original/image.jpg 
rails_root/public/assets/posts/5/medium/image.jpg 
rails_root/public/assets/posts/5/thumb/image.jpg 

迁移

class AddAttachmentImageToPosts < ActiveRecord::Migration 
    def self.up 
    add_attachment :posts, :photo 
    end 

    def self.down 
    remove_attachment :posts, :photo 
    end 
end 

模式:

create_table "posts", :force => true do |t| 
    t.string "title" 
    t.text  "body" 
    t.datetime "date" 
    t.string "poster" 
    t.boolean "feature" 
    t.datetime "created_at",   :null => false 
    t.datetime "updated_at",   :null => false 
    t.string "image_file_name" 
    t.string "image_content_type" 
    t.integer "image_file_size" 
    t.datetime "image_updated_at" 
    end 

然而,当视图显示,它无法找到该图像。我在这里错过了什么?

回答

1

尝试使用attr_accessible而不是attr_accessor作为照片列。

所以

class Post < ActiveRecord::Base 

    attr_accessible :body, :date, :feature, :poster, :title, :photo, :photo_file_name, :photo_content_type, :photo_file_size, :photo_updated_at 

    has_attached_file :photo, :styles => { :medium => "300x300>", :thumb => "100x100>" }, 
       :url => "/assets/posts/:id/:style/:basename.:extension", 
       :path => ":rails_root/public/assets/posts/:id/:style/:basename.:extension" 
end 

编辑更新后:

有你的数据库和你的曲别针设置不匹配。请将所有列更改为photo_x或更改将照片转为图像的设置。

+0

这是我原来的。当我这样做时,我得到: 需要post模型attr_accessor'photo_file_name' – unmuse

+0

您的模式对Post来说是什么样子?我认为正在发生的是您的数据库中缺少的那些列。因此,当您添加访问器时,问题似乎消失了,但当然,因为再次加载对象时没有任何内容保存到数据库,与上载对象有关的数据会丢失,因此它假定没有上传任何内容。 – rovermicrover

+0

编辑为添加迁移和模式。 – unmuse