Write params需要嵌套属性的函数

时间:2015-06-22 14:20:49

标签: ruby-on-rails ruby

我正在尝试使用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

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

  

{       &#34; UTF8&#34; =&GT; &#34;✓&#34 ;,       &#34; authenticity_token&#34; =&GT; &#34; EPd9Ed7C / qBsKu4R + t3q1Xm8aYSH7M6ZcvbpjHiJ9BnZlX0ldVCIc5AP1zcKaUB4Y7MzY8aLJI + gcPekE / hn6Q ==&#34 ;,       &#34;附件&#34; =&GT; {           &#34;文件&#34; =&GT; #&lt; ActionDispatch :: Http :: UploadedFile:0x007f8612bab4f0 @ tempfile =#&lt; Tempfile:/ var / folders / ft / 6   m5lh5sd2bb3dwj8pczwdjtm0000gn / T / RackMultipart20150622 - 5173 - 1   dfsg86.jpg&gt; ,@ original_filename =&#34; Kesari_bhath.jpg&#34;,@ content_type   =&#34; image / jpeg&#34;,@ header =&#34; Content-Disposition:form-data;命名= \&#34;附件[文件] \&#34 ;;   filename = \&#34; Kesari_bhath.jpg \&#34; \ r \ nConContent-Type:image / jpeg \ r \ n&#34; &GT;       },       &#34;提交&#34; =&GT; &#34;保存附件&#34; }

因此,我可以@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 :(得分:1)

您可以试试这个:

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

答案 1 :(得分:0)

您可以尝试这样的事情:

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

答案 2 :(得分:0)

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

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