【问题标题】:Polymorphic Nested Form with Paperclip in Rails 3.1.3Rails 3.1.3 中带有回形针的多态嵌套表单
【发布时间】:2011-12-05 04:59:37
【问题描述】:

我的模型:

class NewsItem < ActiveRecord::Base
  has_many :file_uploads, :as => :uploadable
  accepts_nested_attributes_for :file_uploads, :allow_destroy => true
end


class FileUpload < ActiveRecord::Base
  belongs_to :uploadable, :polymorphic => true
  has_attached_file :upload, :styles => {:thumb => '100x100>'}
end

表单代码(嵌套在 NewsItem 中)

...

<%= f.fields_for :file_uploads do |upload| %>
  <div class="file_upload">
    <%= upload.file_field :upload %>
  </div>

  ...

<% end %>

...

提交时出现以下错误:“未知属性:上传”。以下是参数:

{"utf8"=>"✓",
 "authenticity_token"=>"MBfxJ4XTizCXv3Mpu971VHCm60bS3Y84Kdxfe+VJD2w=",
 "news_item"=>{"title"=>"",
 "body"=>"",
 "published_date"=>"",
 "file_uploads_attributes"=>{"0"=>{"upload"=>#<ActionDispatch::Http::UploadedFile:0x000001070112a8 @original_filename="rails-dd352fc2630e5f9aa5685ef1d7fe5997.png",
 @content_type="image/png",
 @headers="Content-Disposition: form-data; name=\"news_item[file_uploads_attributes][0][upload]\"; filename=\"rails-dd352fc2630e5f9aa5685ef1d7fe5997.png\"\r\nContent-Type: image/png\r\n",
 @tempfile=#<File:/var/folders/hb/2bkct63171lck8d3sg0xfq0c0000gn/T/RackMultipart20111204-3216-71in7a>>,
 "name"=>"",
 "caption"=>""}}},
 "commit"=>"Create News item"}

我正在使用 Rails 3.1.3 和回形针“~> 2.4”。

【问题讨论】:

  • 我认为您需要先构建一个 file_upload 对象,然后才能在nested_form 中使用它。另外,也许你需要添加 attr_accessible :file_uploads_attributes (虽然不确定多态是如何工作的)。

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 paperclip


【解决方案1】:

我会避免使用诸如“可上传”之类的通用术语,因为由此产生的术语“上传”可能会发生冲突。

youavmatchulsky 的建议也很好 - 如果您在任何需要使 file_uploads_attributes 可访问的地方都有 attr_accessible。

另外,参数看起来不像是多部分的,所以我会在调用 form_for 时使用 :multipart => true 来强制它

编辑:即使它 supposed 自动发生,您可能必须明确地 accept_nested_attributes_for 加入,然后在加入模型上 accept_nested_attributes_for :uploadable - 我发现 anaf 很奇怪有时像多态连接之类的东西

【讨论】:

    【解决方案2】:

    重新启动 rails 应用程序解决了这个问题。我猜我安装了 gem 但没有重新启动,导致上面的错误。经验教训:安装 gem 后总是重启。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-22
      相关资源
      最近更新 更多