Rails accepted_nested_attributes_for多态强参数

时间:2015-08-09 00:18:41

标签: ruby-on-rails

我有一个与附件表具有多态关联的文章模型。

在新文章表单中,我要求用户能够上传附件。

代码的作用不是强大的参数,因为我不知道将什么作为多态关系的强对数。

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哈希如下:

{"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"}

1 个答案:

答案 0 :(得分:1)

在我看来,您正尝试使用 Carrierwave 添加多个文件附件。

为了使其正常工作,您需要在article_params ...

中指定以下内容
def article_params
  params.require(:article).permit(:content, attachments_attributes: [:id, :attachable_id, :name])
end

如您所见,您需要指定3个参数。指定关联/关系需要:id:attachable_id:name是文件/路径的名称。

我希望这可以帮助你,蒂姆。