Error (Could not find the inverse association for profile_image_attachment (:record in ActiveStorage::Attachment)):

116 Views Asked by At

In my app/models/active_storage/attachment.rb file I had used this code

class ActiveStorage::Attachment < ApplicationRecord
  belongs_to :blob, class_name: "ActiveStorage::Blob

  def self.ransackable_attributes(auth_object = nil)
    ["blob_id", "created_at", "id", "name", "record_id", "record_type"]
  end
end

When creating Active Admin with Active Storage, I encountered a search error. To address this, I used defined the ransackable method in my model. In my app/models/user.rb I had used

has_one_attached :profile_image

When I open this link http://127.0.0.1:3000/users/1 it show this error:

unknown keywords: :class_name, :as, :inverse_of

And when I open this link http://127.0.0.1:3000/admin it open successfully

enter image description here

I had used inverse of in my app/models/user.rb file, but it did't work I had go through all my schema file it generate activestorage of correctly.

1

There are 1 best solutions below

0
mechnicov On

You shouldn't define or redefine any association in built-in ActiveStorage::Attachment class. And of course you shouldn't change inheritance of this class!

Look to the source and you will see that parent class is ActiveStorage::Record. And belongs_to :blob has autosave option

If you need to allow search with ransack, just reopen this class with ransack method. Define only ransack method, don't change other things

You can use initializer to patch built-in classes

# config/initializers/active_storage.rb

ActiveSupport.on_load(:active_storage_attachment) do
  class ActiveStorage::Attachment < ActiveStorage::Record
    def self.ransackable_attributes(auth_object = nil)
      %w[blob_id created_at id name record_id record_type]
    end
  end
end

Please note on_load hook here, it is from source code above. And it is important moment because you can successfully patch only if needed class is already loaded

Also note that inheritance is different in older rails: ActiveStorage::Attachment's parent class in 5.2 and 6.0 versions is ActiveRecord::Base. And 5.2 doesn't support hooks