0

我正在使用 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
4

1 回答 1

0

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

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

它就像一个魅力:)

于 2013-10-01T21:01:53.283 回答