警告:无法批量分配受保护的属性(使用回形针)

时间:2012-02-01 17:17:44

标签: ruby-on-rails ruby-on-rails-3 associations paperclip nested-attributes

我认为由于此警告,附件不会保存在数据库中。我尝试了不同的attr_accessible属性变体,但我总是得到这个警告或错误“unknown attribute:upfile”。所以,我的代码:

post.rb

class Post < ActiveRecord::Base
  has_many :comments, :as => :commentable
  belongs_to :user
  has_many :attaches, :as => :uploadable, :dependent => :destroy

  attr_accessible :title, :body, :commentable, :attach_attributes
  accepts_nested_attributes_for :attaches
end

attach.rb:

require 'paperclip'
class Attach < ActiveRecord::Base
  belongs_to :uploadable, :polymorphic => true

  has_attached_file :upfile
  attr_accessible :upfile
end

警告:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"m+81lxu25R0Fu2bHUJthIBU265V+kDo+6wcL3BcFwoc=", "post"=>{"title"=>"sdfsdfsdf", "body"=>"sdfdsfsdfsd", "commentable"=>"0", "upfile"=>#<ActionDispatch::Http::UploadedFile:0x00000003d35290 @original_filename="www.rubyonrails (1).com", @content_type="application/octet-stream", @headers="Content-Disposition: form-data; name=\"post[upfile]\"; filename=\"www.rubyonrails (1).com\"\r\nContent-Type: application/octet-stream\r\n", @tempfile=#<File:/tmp/RackMultipart20120201-2498-1ef2jve>>}, "commit"=>"Submit"}
WARNING: Can't mass-assign protected attributes: upfile

如果我将attr_accessible更改为“:title,:body,:commentable,:upfile”,我会收到此错误:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"m+81lxu25R0Fu2bHUJthIBU265V+kDo+6wcL3BcFwoc=", "post"=>{"title"=>"dfsdf", "body"=>"sdfsdfsdf", "commentable"=>"0", "upfile"=>#<ActionDispatch::Http::UploadedFile:0x007f011c0559f0 @original_filename="www.rubyonrails (1).com", @content_type="application/octet-stream", @headers="Content-Disposition: form-data; name=\"post[upfile]\"; filename=\"www.rubyonrails (1).com\"\r\nContent-Type: application/octet-stream\r\n", @tempfile=#<File:/tmp/RackMultipart20120201-2498-qvfih5>>}, "commit"=>"Submit"}
Completed 500 Internal Server Error in 4ms
ActiveRecord::UnknownAttributeError (unknown attribute: upfile):

使用ruby 1.9.3,rails 3.2.0,paperclip 2.5.2

1 个答案:

答案 0 :(得分:1)

问题在于观点。需要将fields_for用于嵌套资源:

<%= f.fields_for :attaches do |a| %>
  name: <%= a.text_field :name %>
  attach: <%= a.file_field :upfile %>
<% end %>

在post.rb和attaches.rb

中没有attr_accessible