Rails 4 Carrierwave在更新时重复输入

时间:2013-10-01 03:54:28

标签: ruby-on-rails duplicates carrierwave

我正在使用Carrierwave gem将附件模块添加到我的应用程序中。为此,我创建了一个名为Attachable的模型关注点,如下所示:

module Attachable
  extend ActiveSupport::Concern

  included do
    has_many :attachments, as: :attachable, dependent: :destroy
    accepts_nested_attributes_for :attachments
  end
end

我正在调用我的帖子模型:

class Post < ActiveRecord::Base
  include Attachable
end

如果它可以正常保存新帖子:

def create
  @post = current_user.posts.new( post_params )
  if @post.save
    redirect_to post_path(@post.slug)
  else
    @categories = Term.get_category
    render :new
  end
end

当我更新时,它实际上复制了我的条目(数据库):

def update
  @post.clean_taxonomies
  if @post.update( post_params )
    redirect_to post_path(@post.slug)
  else
    @categories = Term.get_category
    render :edit
  end
end

编辑时,它会重新填充所有附件标题(字段名称:我的表中的字符串),但由于它无法将文件名重新填充到input field中,因此当我保存修改时,它会复制附件数量用空文件。

如果已经定义了附件,我该如何修复并上传/保存附件?

由于

编辑:
以下是posts/edit.html.haml上的观点来源(与new.html.haml相同):

= form_for @product, url: product_path(@product.slug), html: { multipart: true } do |f|
  = f.fields_for :attachments do |attachment|
    .row.attachment
      .col-sm-6
        = attachment.label :name, 'Filename'
        = attachment.text_field :name, class: 'form-control'
      .col-sm-5.col-xs-9
        = attachment.label :file, 'File'
        = attachment.file_field :file, class: 'form-control'
      .col-sm-1.col-xs-1
        %a.remove-attachment{ href: '#' }
          %i.icon-remove-circle.icon-2x

1 个答案:

答案 0 :(得分:0)

好的,我终于找到了解决方案。我需要在reject_if上使用accepts_nested_attributes_for作为:

accepts_nested_attributes_for :attachments,
                              allow_destroy: true,
                              reject_if: lambda { |a| a['file'].blank? }

它就像一个魅力:)