我正在尝试为文件上传设置多态关联。现在等待下面的代码,有两个问题需要很长时间。我搜索了很多,但仍然找不到解决方案
#post.rb
class Post < ActiveRecord::Base
attr_accessible :content,:tags_attributes, :attachments_attributes
has_many :tags
has_many :attachments, :as => :attachable
accepts_nested_attributes_for :attachments
end
#attachment.rb
class Attachment < ActiveRecord::Base
belongs_to :attachable, :polymorphic => true
attr_accessible :description, :file
mount_uploader :file, FileUploader
end
# _form.html.erb
<%= form_for @post , :html=>{:multipart => true } do |post_form| %>
<%= post_form.fields_for :attachments do |attachment_form| %>
<p>hello</p>
<p>
<%= attachment_form.label :description %><br />
<%= attachment_form.text_area :description %>
</p>
<p>
<%= attachment_form.label :file %><br />
<%= attachment_form.file_field :file %>
</p>
<% end %>
<%= post_form.submit %>
<% end %>
它只会在页面上显示一个按钮,但表单部分在哪里?我觉得这里fields_for的用法是对的,因为我之前已经定义了一个标签模型,访问的机制几乎是一样的。我使用<%= post_form.fields_for 的格式:tags do |tag_form| %>,但是为什么当涉及到多态时它什么也没显示?
作为问题 1 的临时修复,我将fields_for语句更新为下面,表单现在显示在页面上,但是当我按下提交按钮时,它会提示以下问题Can't mass-assign protected attributes: attachment
<%= post_form.fields_for @post.attachments.build do |attachment_form| %>
谁能帮我解决这两个问题?