Skip to content

Instantly share code, notes, and snippets.

@zackexplosion
Last active January 21, 2019 05:20
Show Gist options
  • Save zackexplosion/664e3360f1ad867ffd482abe356edad3 to your computer and use it in GitHub Desktop.
Save zackexplosion/664e3360f1ad867ffd482abe356edad3 to your computer and use it in GitHub Desktop.

migration

class AddUploadableToUploadFile < ActiveRecord::Migration[5.2]
  def change
    add_reference :upload_files, :uploadable, index: true
  end
end

models/upload_file.rb

class UploadFile < ApplicationRecord
  belongs_to :uploadable, :polymorphic => true
  belongs_to :project,
    class_name:  "DecorateProject",
    foreign_key: 'project_id',
    optional: true

  serialize :addition
end

models/product.rb

....
  has_many :uploadable, :as => :standard_quotation
....

以上同樣的寫法在現行專案會報錯誤 NameError: uninitialized constant Product::StandardQuotation,但開一個全空的rails專案不會,目前想到的方法是把gemfile裡面裝的套件一個一個搬過去空白專案試.

Development [4] courcasa-membership(main)> Product.first.standard_quotation
  Product Load (0.7ms)  SELECT  `products`.* FROM `products` ORDER BY `products`.`id` ASC LIMIT 1
NameError: uninitialized constant Product::StandardQuotation
from /Users/zack/.rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/activerecord-5.2.1/lib/active_record/inheritance.rb:196:in `compute_type'

inheritance.rb

        # Returns the class type of the record using the current module as a prefix. So descendants of
        # MyApp::Business::Account would appear as MyApp::Business::AccountSubclass.
        def compute_type(type_name)
          if type_name.start_with?("::".freeze)
            # If the type is prefixed with a scope operator then we assume that
            # the type_name is an absolute reference.
            ActiveSupport::Dependencies.constantize(type_name)
          else
            type_candidate = @_type_candidates_cache[type_name]
            if type_candidate && type_constant = ActiveSupport::Dependencies.safe_constantize(type_candidate)
              return type_constant
            end

            # Build a list of candidates to search for
            candidates = []
            name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" }
            candidates << type_name

            candidates.each do |candidate|
              constant = ActiveSupport::Dependencies.safe_constantize(candidate)
              if candidate == constant.to_s
                @_type_candidates_cache[type_name] = candidate
                return constant
              end
            end

196 >>      raise NameError.new("uninitialized constant #{candidates.first}", candidates.first)
          end
        end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment