2015-08-09 31 views
0

我有一个与附件表有多态关联的文章模型。Rails accept_nested_attributes_for多态强参数

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

该代码的作品不是强烈的参数,因为我不知道如何将这个多态关系的强参数放在什么位置。

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

这将有助于将这一行'accep_nested_attributes_for:attachments'添加到文章模型。并在article_params中使用它:'params.require(:article).permit(:content,attachments_attributes:[attachment:[]])' – Athar

回答

1

看来

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 

附着模型的结构如下对我来说,你正试图添加多ple文件附件使用Carrierwave

为了这个工作,你需要指定article_params以下内...

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

正如你可以看到你需要指定3个PARAMS。需要:id:attachable_id来指定关联关系,并且:name是文件/路径的名称。蒂姆,我希望这可以帮助你。