Search code examples
ruby-on-railsrubygemsrails-activestoragemodel-associations

Rails Active Storage unable to find a valid model association


I hope you are doing good. I am trying to do is shift paper clip functionality to active storage but I am facing this issue for the past two days but unable to find a solution for it. Maybe you can help me with it.

I've two models library_document.rb and document.rb

The models have the following associations, with each other:

class LibraryDocument < ApplicationRecord

belongs_to :document

end
class Document < ApplicationRecord
  belongs_to :company
  has_many :library_documents, foreign_key: "document_id", dependent: :nullify
  
  do_not_validate_attachment_file_type :attached_file
  has_one_attached :attached_file
  validates_attachment :attached_file,
                        size: { less_than: 5.megabytes, message: 'File is too large' }
end

When I run try to access documents in index method in library_documents_controller, in the following way:

class LibraryDocumentsController < AuthenticatedController

  def index
    documents = @current_company.documents
    render json: { documents: documents}
  end
end

it gives me the following error:

NameError - Rails couldn't find Document association. Please provide the :class_name option on the association declaration. If :class_name is already provided, make sure it's an ActiveRecord::Base subclass.:
  app/controllers/library_documents_controller.rb:6:in `index'
  app/controllers/application_controller.rb:41:in `block in set_user_time_zone'
  app/controllers/application_controller.rb:41:in `set_user_time_zone

Moreover, on doing Document.last in rails console it gives me the following error:

NoMethodError: undefined method `before_attached_file_post_process' for Document:Class
Did you mean?  before_avatar_post_process
from /home/ubuntu/.rvm/gems/ruby-3.0.4/gems/activerecord-7.0.2.4/lib/active_record/dynamic_matchers.rb:22:in `method_missing'

Sorry the question seems very long, but I tried my best to explain my problem.


Solution

  • I think you should change the code in Msp::Templates::Document model.

    From this

    validates_attachment :attached_file,
                         size: { less_than: 5.megabytes, message: 'File is too large' }
    

    To

    validates :attached_file,
               size: { less_than: 5.megabytes, message: 'File is too large' }
    

    It seems like the method before_attached_file_post_process belongs to the paperclip gem, and you are not using it anymore.