【发布时间】:2023-04-10 04:26:01
【问题描述】:
我有一个与附件表具有多态关联的文章模型。
在新文章表单中,我要求用户能够上传附件。
除了强参数之外,代码还可以工作,因为我不知道将什么作为多态关系的强参数。
def create
@article = Article.build(article_params)
@article.user_id = current_user.id
if @article.save
params[:article_attachments]['attachment'].each do |a|
@article.attachments.create!(:file => a)
end
respond_to do |format|
format.html {redirect_to article_path(@article)}
format.js
end
else
render 'new'
end
end
private
# Never trust parameters from the scary internet, only allow the white list through.
def article_params
params.require(:article).permit(:content, attachments_attributes: [])
end
附件模型结构如下:
Attachment
=> Attachment(id: integer, file: string, attachable_id: integer, attachable_type: string, created_at: datetime, updated_at: datetime)
嵌套形式为:
<div class="uploader pull-left" >
<%= f.fields_for :attachments do |builder| %>
<%= builder.file_field :file, :multiple => true, accept: 'image/jpeg,image/gif,image/png', name: "discussion_attachments[attachment][]" %>
<% end %>
</div>
params hash 如下:
{"utf8"=>"✓", "authenticity_token"=>"m84LL1D05LCsivXuASukGgcDoVhTvxhVuDThv9Q2iDRS/AMOeMvQArc0mpMZJSsW887R2krWu85Xm1v9+WQ8bQ==", "article"=>{"content"=>""}, "attachments"=>{"file"=>[#<ActionDispatch::Http::UploadedFile:0x007f0918ffb720 @tempfile=#<Tempfile:/tmp/RackMultipart20150810-3911-1rsq9lz.JPG>, @original_filename="YourPhoto_0001.JPG", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"attachments[file][]\"; filename=\"YourPhoto_0001.JPG\"\r\nContent-Type: image/jpeg\r\n">, #<ActionDispatch::Http::UploadedFile:0x007f0918ffb338 @tempfile=#<Tempfile:/tmp/RackMultipart20150810-3911-i1ztf2.JPG>, @original_filename="YourPhoto_0002.JPG", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"attachments[file][]\"; filename=\"YourPhoto_0002.JPG\"\r\nContent-Type: image/jpeg\r\n">]}, "commit"=>"Submit", "controller"=>"articles", "action"=>"create"}
【问题讨论】:
-
这会有所帮助吗,将这行
accepts_nested_attributes_for :attachments添加到文章模型中。并在 article_params 中使用它:params.require(:article).permit(:content, attachments_attributes: [attachment: []])
标签: ruby-on-rails