1

由於此警告,我認爲附件未保存在數據庫中。我嘗試了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): 

使用紅寶石1.9.3,rails 3.2.0,回形針2.5.2

回答

1

問題出在視圖中。需要使用fields_for嵌套資源:

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

而且在post.rb沒有attr_accessible和attaches.rb

相關問題