关于图像:带有嵌套模型的 Rails 和 Paperclip:从表单上传不起作用

Rails and Paperclip with nested models: uploads from form not working

我目前正在尝试制作一个照片库应用程序,其中照片只能通过画廊界面访问。画廊 => has_many :照片,照片 => 所属:画廊。所有这些都运行良好。

然而,现在我想给我的照片一个附件:图像。我做了 Neath 在他的教程中所说的一切,我刚刚添加了 validates_attachment_presence :image。在验证之前,照片模型工作正常,只是在保存带有图像的模型后,图像从未出现。现在,通过验证,在选择要上传的图像后,我得到一个 :flash =>

1
2
3
4
5
1 error prohibited this photo from being saved

There were problems with the following fields:

    * Image file name must be set.

那么这里发生了什么?相关代码如下:

模型/照片

1
2
3
4
5
6
7
8
9
10
 class Photo < ActiveRecord::Base
    attr_accessible :gallery_id, :name, :rating

    belongs_to :gallery
    validates_associated :gallery

    has_attached_file :image
    validates_attachment_presence :image

  end

意见/照片/_form.html.erb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<% form_for [@gallery, @photo], :html => { :multipart => true } do |f| %>
  <%= f.error_messages %>
  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <p>
    <% if @photo.image? %>
      <%= image_tag @photo.image.url %><br />
      <%= link_to @photo.image.url, @photo.image.url %>
    <% end %>
    <%= f.label :image %><br />
    <%= f.file_field :image %>
  </p>
  <p><%= f.submit %></p>
<% end %>

模型/画廊.rb

1
2
3
4
5
6
7
class Gallery < ActiveRecord::Base
  attr_accessible :name, :user_id, :shoot_date

  # destroy all photos when a gallery is destroyed
  has_many :photos, :dependent => :destroy

end

我想我已经正确设置了多部分表单,而且我想我以前在尝试没有嵌套模型的回形针模型时遇到过这个问题。我错过了什么吗?

更新:这是尝试上传交易的 Mongrel 输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Processing PhotosController#update (for 127.0.0.1 at 2010-12-05 14:19:29) [PUT]
  Parameters: {"photo"=>{"name"=>"blah","image"=>#<File:/tmp/RackMultipart20101205-2909-wo2g7z-0>},"commit"=>"Save changes","id"=>"10","gallery_id"=>"3"}
  Gallery Columns (0.6ms)   SHOW FIELDS FROM `galleries`
  Gallery Load (0.1ms)   SELECT * FROM `galleries` WHERE (`galleries`.`id` = 3)
  Photo Columns (0.7ms)   SHOW FIELDS FROM `photos`
  Photo Load (0.1ms)   SELECT * FROM `photos` WHERE (`photos`.`id` = 10 AND (`photos`.gallery_id = 3))
WARNING: Can't mass-assign these protected attributes: image
  SQL (0.1ms)   BEGIN
  CACHE (0.0ms)   SELECT * FROM `galleries` WHERE (`galleries`.`id` = 3)
  SQL (0.1ms)   ROLLBACK
Rendering template within layouts/application
Rendering photos/edit
Rendered photos/_form (64.1ms)
Completed in 83ms (View: 67, DB: 2) | 200 OK [http://localhost/galleries/3/photos/10]

想通了。将杂种输出扔到谷歌,然后我们开始:

http://railsforum.com/viewtopic.php?id=35544

基本上,他们忘记告诉您将 :image 添加到 attr_accessible 列表中。

1
2
3
4
5
6
7
8
9
10
11
Photo model changed to
class Photo < ActiveRecord::Base
    attr_accessible :gallery_id, :name, :rating, :image

    belongs_to :gallery
    validates_associated :gallery

    has_attached_file :image
    validates_attachment_presence :image

  end