【问题标题】:Write params require function for nested attributes为嵌套属性编写参数需要函数
【发布时间】:2015-09-08 01:06:28
【问题描述】:

我正在尝试使用 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+t3q1Xm8aYSH7M6ZcvbpjHiJ9BnZlX0ldVCIc5AP1zcKaUB4Y7MzY8aLJI+gcPekE/hn6Q==", “附件”=> { "file" => # , @original_filename = "Kesari_bhath.jpg", @content_type =“图像/jpeg”,@headers =“内容处置:表单数据;名称=\”附件[文件]\”; filename=\"Kesari_bhath.jpg\"\r\nContent-Type: image/jpeg\r\n" > }, "提交" => "保存附件" }

所以我可以以params[:attachment]['file'].original_filename 的身份访问@original_filname

params.require(第 17 行)这个嵌套属性怎么写?

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

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    你可以试试这样的:

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

    【讨论】:

      【解决方案2】:

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

      允许我在以file 为键的散列中获取值。

      【讨论】:

        【解决方案3】:

        你可以试试这个:

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

        【讨论】:

        • 上面写着unknown attribute 'file' for Attachment。我忽略了什么吗?这是否与 file 在这里不是符号这一事实有关?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-05-05
        • 2021-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-27
        相关资源
        最近更新 更多