'Rails Active Storage NoMethodError - undefined method `[]' for nil:NilClass:

I am receiving "NoMethodError - undefined method `[]' for nil:NilClass:" when trying to attach a picture to a model. I am using Rails 6 in API mode.

The Model:

    has_one_attached :profile_picture

Relevant Tables in Schema:

    t.string "name", null: false
    t.string "record_type", null: false
    t.bigint "record_id", null: false
    t.bigint "blob_id", null: false
    t.datetime "created_at", null: false
    t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id"
    t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true
  end

  create_table "active_storage_blobs", force: :cascade do |t|
    t.string "key", null: false
    t.string "filename", null: false
    t.string "content_type"
    t.text "metadata"
    t.bigint "byte_size", null: false
    t.string "checksum", null: false
    t.datetime "created_at", null: false
    t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true
  end

  add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id"

Route I am using:

    namespace :tenants, defaults: {format: :json} do
      post '/upload_picture/:id', to: 'tenants#upload_picture'

Controller method:

        tenant = Tenant.find_by(id: params[:id])
        tenant.profile_picture = params[:profile_picture] if params[:profile_picture]
        if tenant.save
            render json: tenant
        else
            render json: tenant.errors.full_messages
        end
    end

Link to Postman request parameters I am sending form-data in the body, with the key of 'profile_picture' pointings to the desired picture, which is stored locally.

The response is never completed; the server halts after trying to attach the picture and kicks back the error message.

In the console, tenant.profile_picture.attached? properly returns as false. However, if I try to attach a file with tenant.profile_picture.attach(io: <picture>, filename: 'name'>) or tenant.profile_picture = <picture>, I receive the same error after asking tenant.profile_picture.attached?



Solution 1:[1]

I wonder your problem is here.

tenant.profile_picture = params[:profile_picture] if params[:profile_picture]

should be

tenant.profile_picture.attach(params[:profile_picture]) if params[:profile_picture]

Take a look at the documentation for active storage

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sethi