【问题标题】:Rails: Undefined method `[]=' for nil:NilClass with active record when no attachmentsRails:nil的未定义方法`[] =':NilClass在没有附件时具有活动记录
【发布时间】:2021-04-04 14:55:37
【问题描述】:

我正在使用 wicked gem 作为巫师形态。在我的表单的一个步骤中,我有上传附件的字段。我正在使用主动存储和 Rails 6。

在我看来

<%= f.file_field :plan %>
<%= f.file_field :appraisal %>
<%= f.file_field :flow %>

在我的 sale_steps 控制器中

      def show
        @sale = current_user.sales.find(params[:sale_id])
        render_wizard
      end

      def update
        @sale = current_user.sales.find(params[:sale_id])
        params[:sale][:status] = step.to_s **(the error is on this line)**
        @sale.update(sale_params)
        render_wizard @sale
      end
    
      def sale_params
          params.require(:sale).permit(.... :plan, :appraisal, :flow)
      end

在我的模型中

    has_one_attached :plan
    has_one_attached :appraisal
    has_one_attached :flow

    validates :location,  presence: true, if: -> { status?(:second_step) }

    def status?(step_key)
      status == step_key.to_s  (this is to allow validations on each step - I have no validations defined for my attachments)
    end
    

在我的表单中,当我到达向导的最后一步上传附件时,只要至少有一个附件存在,它就可以正常工作。但是,如果没有附件,我会在更新点击时收到以下无方法错误:

    undefined method `[]=' for nil:NilClass
    {"_method"=>"put", "authenticity_token"=>"[FILTERED]", "commit"=>"Continue", "sale_id"=>"37", "id"=>"fourth_step"}

我只是想知道为什么会这样(这与邪恶的宝石或其他什么有关?)有没有我可以尝试的解决方案?太棒了

【问题讨论】:

  • 发生错误是因为您在 params[:sale][:status] 中调用 []=,但 params[:sale] 为 nil,因为我认为它与任何 gem 无关,而是您如何修改来自params ActionController::Parameters 对象的值。

标签: ruby-on-rails activerecord ruby-on-rails-6 wicked-gem


【解决方案1】:

根据错误,当没有上传附件时params[:sale]的值为nil。因此,当您尝试设置params[:sale][:status] 时,它会给出undefined method []=' for nil:NilClas 错误。在将值分配给 params[:sale][:status] 之前,您应该在 params[:sale] 上添加存在检查。

【讨论】:

  • 谢谢。理解!我正在阅读 Wicked wiki,它在 github.com/zombocom/wicked 处提到了“case step if....”。但我不知道这里的语法如何用于对我的三个上传进行存在检查?再次感谢。很有帮助。
  • 试试-params[:sale][:status] = step.to_s if params[:sale].present?
  • 错误参数丢失或值为空:之后出售(尽管其他步骤仍然有效)
【解决方案2】:

我得到了这个工作。

如果有人碰巧偶然发现了这个问题 - 在向导的最后一步页面上,我只有文件上传字段。当我输入一个额外的随机输入字段时,它现在可以正常工作了。

感谢您的指导。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 2014-06-01
    相关资源
    最近更新 更多