Rails Active Storage 无法找到有效的模型关联

问题描述 投票:0回答:0

我希望你做得很好。 我想做的是将回形针功能转移到活动存储,但过去两天我一直面临这个问题,但无法找到解决方案。也许你可以帮助我。

我有两个模型,以及各自的 msp 模板控制器 library_document.rb 和 document.rb

模型之间有以下关联:

class LibraryDocument < ApplicationRecord

belongs_to :msp_templates_document, class_name: "Msp::Templates::Document", foreign_key: "msp_templates_document_id", optional: true
class Msp::Templates::Document < ApplicationRecord
  belongs_to :company
  has_many :library_documents, foreign_key: "msp_templates_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

当我运行时尝试访问 library_documents_controller 中索引方法中的 msp_templates_documents,方法如下:

class Msp::Templates::LibraryDocumentsController < AuthenticatedController

  def index
    msp_templates_documents = @current_company.msp_templates_documents.order("name ASC").select(:id, :name, :attached_file_content_type, :attached_file_file_name, :attached_file_file_size, :attached_file_updated_at)
    render json: { msp_templates_documents: msp_templates_documents}
  end
end

它给了我以下错误:

NameError - Rails couldn't find a valid model for Msp::Templates::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/msp/templates/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

此外,在 Rails 控制台中执行 Msp::Templates::Document.last 时,出现以下错误:

NoMethodError: undefined method `before_attached_file_post_process' for Msp::Templates::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'

对不起,这个问题似乎很长,但我尽力解释了我的问题。

ruby-on-rails rubygems rails-activestorage model-associations
© www.soinside.com 2019 - 2024. All rights reserved.