以嵌套形式上载Carrierwave图像仍然创建记录甚至没有指定文件

时间:2011-10-01 18:59:59

标签: ruby-on-rails nested-forms carrierwave simple-form

我在嵌套的simple_form中上传Carrierwave图像,除非用户没有指定文件,否则它会起作用(在某种情况下),除非之前存在,否则会创建空白的Picture对象。不太确定如何制作它,以便如果用户没有指定要上传的“新”图像,则不会删除旧图像和/或创建没有文件的空白记录。

我正在做的一件事(也许是奇怪的事情)总是将登录的@user发送给用户#edit action,然后构建一个@ user.picture,如果它不存在的话。我认为这是我糟糕的设计。

    # user.rb
    class User < ActiveRecord::Base
    [...]

      has_one :picture, :dependent => :destroy
      accepts_nested_attributes_for :picture

    [...]
    end

    # picture.rb
    class Picture < ActiveRecord::Base
      attr_accessible :image, :remove_image
      belongs_to :user
      mount_uploader :image, ImageUploader
    end

    # users_controller.rb
    def edit
      if @user.picture.nil?
        @user.build_picture
      end
    end

    #_form.html.erb
    <%= simple_form_for @user, :html => {:multipart => true} do |f| %>
      <%= render "shared/error_messages", :target => @user %>  
      <h2>Picture</h2>
      <%= f.simple_fields_for :picture do |pic| %>
        <% if @user.picture.image? %>
          <%= image_tag @user.picture.image_url(:thumb).to_s %>     
          <%= pic.input :remove_image, :label => "Remove", :as => :boolean %>
        <% end %>
        <%= pic.input :image, :as => :file, :label => "Picture" %>
        <%= pic.input :image_cache, :as => :hidden %>
      <% end %>
      <br/>
    #rest of form here
    <% end %>

3 个答案:

答案 0 :(得分:2)

我认为我遇到了同样的问题,我通过在accepts_nested_attribute中添加reject_if选项来解决这个问题。因此,在您的示例中,您可以执行类似

的操作
class User < ActiveRecord::Base
[...]

  has_one :picture, :dependent => :destroy
  accepts_nested_attributes_for :picture,
    :reject_if => lambda { |p| p.image.blank? }

[...]
end

答案 1 :(得分:0)

使用build_ *时,它会在对象上设置外键。 (类似于说Picture.new(:user_id =&gt; id))

试试这个

# users_controller.rb
def edit
  if @user.picture.nil?
    @user.picture = Picture.new
  end
end

答案 2 :(得分:0)

今天我遇到了同样的问题,我解决了这个问题:

  accepts_nested_attributes_for :photos,
    :reject_if => :all_blank