2

我目前正在尝试制作一个照片库应用程序,其中的照片只能通过图库界面访问。图库 => has_many :photos,照片 => belongs_to :gallery。所有这些工作正常。

但是,现在我正在尝试给我的照片一个附件:image。我做了 Neath 在他的教程中所说的一切,我刚刚添加了 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 %>

模型/画廊.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]
4

1 回答 1

3

弄清楚了。将 mongrel 输出扔到 google 中,然后我们开始:

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
于 2010-12-05T19:43:00.547 回答