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

时间:2010-12-05 19:29:01

标签: ruby-on-rails image nested paperclip multipartform-data

我目前正在尝试制作照片库应用程序,其中照片只能通过图库界面访问。 Gallery => has_many:照片,照片=> belongs_to:画廊。所有这一切都很好。

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

1 error prohibited this photo from being saved

There were problems with the following fields:

    * Image file name must be set.

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

模型/照片

 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

<% 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 %>

模型/ gallery.rb

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输出:

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]

1 个答案:

答案 0 :(得分:3)

想出来。将杂种输出扔到谷歌,我们走了:

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

基本上,他们忘了告诉你将:image添加到attr_accessible列表。

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