你好
轨道版本 2.3.5
我正在学习rails,但遇到了问题。
我正在做一些来自 railscasts 教程的嵌套表格。我将文本区域更改为数据字段以上传照片,一切正常。
现在我必须显示上传的图片,我根本做不到。我尝试了我在网上可以找到的所有东西,但没有任何效果。
问题
我有处理文章 CRUD 的文章控制器。在文章新表单中嵌套了一个用于上传图像的表单。
物品控制器
def code_image
@image_data = Photo.find(params[:id])
@image = @image_data.binary_data
send_data(@image, :type => @image_data.content_type,
:filename => @image_data.filename,
:disposition => 'inline')
end
照片模型
def image_file=(input_data)
self.filename = input_data.original_filename
self.content_type = input_data.content_type.chomp
self.binary_data = input_data.read
end
文章/show.html.erb
<%=h @article.title %>
<%=h @article.body %>
<% for photos in @article.photos %>
<%= image_tag(url_for({:action => 'code_image',
:id => @article.photos.id})) -%>
<% end %>
文章/_formnew.html.erb
<% form_for (:article, @article,
:url => {:action=>'create'}, :html=>
{:multipart=>true}) do |f| %>
<%= f.label :title %><br />
<%= f.text_field :title %><br /><br />
<%= f.label :body %><br />
<%= f.text_area :body, :style => 'width: 600px;' %><br /><br />
<% f.fields_for :photos do |builder|%>
<%= builder.label :content, "Photo"%><br />
<%= builder.file_field :image_file %><br />
<% end %>
<br />
<%= f.submit "Create" %>
谢谢