【问题标题】:Rails accepts_nested_attributes_for Polymorphic strong paramsRails 接受_nested_attributes_for 多态强参数
【发布时间】: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


【解决方案1】:

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

为了使其工作,您需要在 article_params... 中指定以下内容...

def article_params
  params.require(:article).permit(:content, attachments_attributes: [:id, :attachable_id, :name])
end

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

我希望这对你有所帮助,蒂姆。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 2011-03-04
    • 2013-12-24
    • 1970-01-01
    • 2012-02-10
    相关资源
    最近更新 更多