1

我有一个具有多个“资产”的模型“文章”,这是一个多态模型,我使用回形针将图像附加到。当我编辑一篇文章时,我希望能够删除旧图像,并在同一笔画中添加新图像。我正在使用 fields_for,它看起来足够通用,因为Rails API 说我可以将它用于特定的资产实例。所以这是我表格的相关部分:

形式:

=f.fields_for :assets do |ff|
  =ff.label "image"
  =ff.file_field :image

-unless @article.assets.first.image_file_name.nil?
  -@article.assets.each do |asset|
    =f.fields_for :assets, asset do |fff|
      =image_tag(asset.image.url(:normal))
      =fff.label "delete image"
      =fff.check_box :_destroy

第一个fields_for是为文章添加图像,第二个部分是删除已经存在的资产。此表单可以添加资产、删除资产,但不能同时进行。这就是问题所在。我怀疑check_box没有足够的指导或什么。

资产模型:

class Asset < ActiveRecord::Base
  belongs_to :imageable, :polymorphic => true

  has_attached_file :image, :styles => { :normal => "100%",:small => "100 x100>",:medium => "200x200>", :thumb => "50x50>" },
                        :storage => :s3, 
                        :s3_credentials => "#{Rails.root}/config/s3.yml", 
                        :path => "/:attachment/:id/:style/:filename"

文章控制器/编辑:

  def edit
    @article = Article.find(params[:id])
    @assets = @article.assets
    if @assets.empty?
      @article.assets.build
    end
  end

我期待看到您的回复。

4

1 回答 1

3

由于我可怜的求救声被置若罔闻,我被迫独自出发(可能是最好的)。我通过摆弄表单的逻辑发现了解决方案。以下是允许我在一个表单提交中添加回形针附件和删除一个(或多个)的设置:

形式:

= form_for(@article, :action => 'update', :html => { :multipart => true}) do |f|
.
.
.
  -@assets.each do |asset|
        =f.fields_for :assets, asset do |asset_fields|
          -if asset_fields.object.image_file_name.nil?
            =asset_fields.label "image"
            =asset_fields.file_field :image
          -else
            =image_tag(asset_fields.object.image.url(:normal))
            =asset_fields.check_box :_destroy

我的设置是:一个articlehas_many assets,它是一个为我保存图像附件的多态模型。

研究:

http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for

创建用于删除属于产品的上传的表单

-第二个链接:提供了在提供object的表单助手上使用方法的洞察力fields_for,在我的情况下,asset_fields.object...它让我可以弄乱@assets

这是感兴趣的文章控制器方法:

  def edit
    @article = Article.find(params[:id])
    @assets = @article.assets
    @article.assets.build
  end
于 2012-06-17T05:33:38.103 回答