首页 文章

Write params需要嵌套属性的函数

提问于
浏览
0

我试图使用Ruby on Rails创建一个简单的文件共享应用程序 . 以下是我的控制器:

1 class AttachmentsController < ApplicationController
  2   def new
  3   end
  4
  5   def create
  6     @attachment = Attachment.new(attachment_params)
  7     @attachment.save
  8     redirect_to @attachment
  9   end
 10
 11   def show
 12     @attachment = Attachment.find(params[:attachment]['file'].original_filename)
 13   end
 14
 15   private
 16   def attachment_params
 17     params.require()
 18   end
 19 end

我上传的文件包含以下格式的参数:

{“utf8”=>“✓”,“authenticity_token”=>“EPd9Ed7C / qBsKu4R t3q1Xm8aYSH7M6ZcvbpjHiJ9BnZlX0ldVCIc5AP1zcKUB4Y7MzY8aLJI gcPekE / hn6Q ==”,“attachment”=> {“file”=>#<ActionDispatch :: Http :: UploadedFile:0x007f8612bab4f0 @ tempfile =#<Tempfile:/ var / folders / ft / 6 m5lh5sd2bb3dwj8pczwdjtm0000gn / T / RackMultipart20150622 - 5173 - 1 dfsg86.jpg>,@ ororinal_filename =“Kesari_bhath.jpg”,@ content_type =“image / jpeg”,@ headers = “Content-Disposition:form-data; name = \”attachment [file] \“; filename = \”Kesari_bhath.jpg \“\ r \ nConContent-Type:image / jpeg \ r \ n”>},“commit” >>“保存附件”}

所以我可以访问 @original_filname 作为 params[:attachment]['file'].original_filename

如何在 params.require (第17行)中编写此嵌套属性?

请注意,哈希是 'file' 而不是 file (请注意引号) . 我无法使用 permit.require(:attachment).permit(:file)permit.require(:attachment).permit('file') 访问它,这两者都会导致 unknown attribute 'file' for Attachment 错误 .

3 回答

  • 0

    你可以试试这个:

    def attachment_params
      params.require(:attachment).permit(:file)
    end
    
  • 1

    params.require(:attachment).permit(params['file'])

    允许我以 file 为键获取哈希值 .

  • 0

    你可以尝试这样的事情:

    params.require(:attachment).permit(... , :file_attributes: [:original_filename])
    

相关问题