【发布时间】:2011-09-15 01:42:26
【问题描述】:
我正在使用 Paperclip 在我的应用中处理个人资料照片上传。他们上传得很好,并根据我的模型中的规格调整大小。但是,如果用户的个人资料 :photo 为零,无论我尝试什么,我都无法更改默认值。这是我要使用的代码:
<% if @profile.photo.nil? %>
<%= image_tag "public/images/example.jpg", :html => { :id => "noUserProfile" } %>
<% else %>
<%= image_tag @profile.photo.url(:normal) %>
<% end %>
我已经尝试过“../public/images/example.jpg”,即使我的公共图像文件夹中有“example.jpg”,这也不起作用。当我在视图中复制图像地址时,我得到:
http://localhost:3000/photos/normal/missing.png
我将这些文件夹添加到我的应用程序中,并在其中放置了一个 missing.png 文件,但什么也没有。如果我转到上面的 URL,我会得到 No route matches "/photos/normal/missing.png"
有人对发生的事情有任何想法吗?
has_attached_file 在 Profile 模型中:
has_attached_file :photo,
:styles => {
:normal => "153x220#",
:small => "75x108#" }
add_attachment_photo_to_profile 迁移:
class AddAttachmentPhotoToProfile < ActiveRecord::Migration
def self.up
add_column :profiles, :photo_file_name, :string
add_column :profiles, :photo_content_type, :string
add_column :profiles, :photo_file_size, :integer
add_column :profiles, :photo_updated_at, :datetime
end
def self.down
remove_column :profiles, :photo_file_name
remove_column :profiles, :photo_content_type
remove_column :profiles, :photo_file_size
remove_column :profiles, :photo_updated_at
end
end
这是在 :photo 存在时呈现的 HTML:
<div class="userSnapshot">
<div class="smFrame">
<div class="smUserPhoto">
<img alt="8217_667699353137_15600054_38423586_7789442_n" src="/system/photos/1/small/8217_667699353137_15600054_38423586_7789442_n.jpg?1316052048" />
</div>
</div>
<div class="findinfo">
<p><a href="/profiles/1">Name</a></p>
</div>
</div>
这是在 :photo 为 nil 时呈现的 HTML:
<div class="userSnapshot">
<div class="smFrame">
<div class="smUserPhoto">
<img alt="Missing" src="/photos/small/missing.png" />
</div>
</div>
<div class="findinfo">
<p><a href="/profiles/2">Name</a></p>
</div>
</div>
【问题讨论】:
-
我认为
has_attached_file是模型级别的“声明”?你为什么不直接说image_tag 'images/example.jpg'?我完全误解了上面的代码吗? -
是的,我也试过
image_tag,但也没有用。显示的照片保存到http://localhost:3000/system/photos/:id/:size/xxxxxx。 -
我不明白。如果头像为 nil,
image_tag应该像任何其他图像一样提供来自/public/images的图像,并且回形针目录不应该进入等式。 -
是的,我不太明白。我已经粘贴了上面生成的 HTML。当
:photo以及:photo为nil时,您可以看到代码显示的内容。 -
回形针会不会使照片不为零?很清楚你的 image_tag 什么时候没有渲染。你的
has_attached_file在模型中是什么样子的? rdocs 有帮助吗?