Programming

Rails 앱에서 모든 모델을 모을 수있는 방법이 있습니까?

procodes 2020. 5. 11. 21:17
반응형

Rails 앱에서 모든 모델을 모을 수있는 방법이 있습니까?


Rails 앱에서 모든 모델을 모을 수있는 방법이 있습니까?

기본적으로 다음과 같은 작업을 수행 할 수 있습니까?-

Models.each do |model|
  puts model.class.name
end

편집 : 의견과 다른 답변을보십시오. 이것보다 더 똑똑한 답변이 있습니다! 또는 이것을 커뮤니티 위키로 향상 시키십시오.

모델은 마스터 객체에 자신을 등록하지 않으므로 Rails에는 모델 목록이 없습니다.

그러나 여전히 응용 프로그램의 models 디렉토리 내용을 볼 수 있습니다 ...

Dir.foreach("#{RAILS_ROOT}/app/models") do |model_path|
  # ...
end

편집 : 또 다른 (야생적인) 아이디어는 Ruby 리플렉션을 사용하여 ActiveRecord :: Base를 확장하는 모든 클래스를 검색하는 것입니다. 그래도 모든 수업을 나열 할 수있는 방법을 모른다 ...

편집 : 그냥 재미를 위해 모든 수업을 나열하는 방법을 찾았습니다.

Module.constants.select { |c| (eval c).is_a? Class }

편집 : 마침내 디렉토리를 보지 않고 모든 모델을 나열하는 데 성공했습니다.

Module.constants.select do |constant_name|
  constant = eval constant_name
  if not constant.nil? and constant.is_a? Class and constant.superclass == ActiveRecord::Base
    constant
  end
end

파생 클래스도 처리하려면 전체 슈퍼 클래스 체인을 테스트해야합니다. Class 클래스에 메소드를 추가하여 수행했습니다.

class Class
  def extend?(klass)
    not superclass.nil? and ( superclass == klass or superclass.extend? klass )
  end
end

def models 
  Module.constants.select do |constant_name|
    constant = eval constant_name
    if not constant.nil? and constant.is_a? Class and constant.extend? ActiveRecord::Base
    constant
    end
  end
end

Rails 3, 4 및 5에 대한 전체 답변은 다음과 같습니다.

cache_classes꺼져있는 경우 (기본적으로 개발 중이지만 프로덕션에서는 켜져 있음) :

Rails.application.eager_load!

그때:

ActiveRecord::Base.descendants

이를 통해 응용 프로그램의 모든 모델이 어디에 있는지,로드되는지, 모델을 제공하는 사용중인 보석도로드되는지 확인합니다.

이것은 Rails 5 ActiveRecord::Base와 같이 ApplicationRecord에서 상속하는 클래스에서 작동 하고 하위 항목의 하위 트리 만 반환합니다.

ApplicationRecord.descendants

이 작업을 수행 하는 방법 에 대한 자세한 내용을 보려면 ActiveSupport :: DescendantsTracker를 확인하십시오 .


누군가이 문제에 걸려 넘어 질 경우를 대비하여 dir 읽기 또는 Class 클래스 확장에 의존하지 않는 다른 솔루션이 있습니다 ...

ActiveRecord::Base.send :subclasses

클래스 배열을 반환합니다. 그럼 당신은 할 수 있습니다

ActiveRecord::Base.send(:subclasses).map(&:name)

ActiveRecord::Base.connection.tables.map do |model|
  model.capitalize.singularize.camelize
end

돌아올 것이다

["Article", "MenuItem", "Post", "ZebraStripePerson"]

추가 정보 model : string unknown 메소드 또는 변수 오류없이 오브젝트 이름에서 메소드를 호출하려면 다음을 사용하십시오.

model.classify.constantize.attribute_names

나는 이것을 할 수있는 방법을 찾고이 방법을 선택하게되었습니다.

in the controller:
    @data_tables = ActiveRecord::Base.connection.tables

in the view:
  <% @data_tables.each do |dt|  %>
  <br>
  <%= dt %>
  <% end %>
  <br>

출처 : http://portfo.li/rails/348561-how-can-one-list-all-database-tables-from-one-project


들어 Rails5의 모델 입니다 이제 서브 클래스ApplicationRecord당신이 당신의 응용 프로그램의 모든 모델의 목록을 얻을 그래서 :

ApplicationRecord.descendants.collect { |type| type.name }

또는 더 짧게 :

ApplicationRecord.descendants.collect(&:name)

개발자 모드 인 경우 다음을 수행하기 전에로드 모델을 열망해야합니다.

Rails.application.eager_load!

나는 테이블리스 모델이 없다면 @hnovick의 솔루션이 멋진 솔루션이라고 생각합니다. 이 솔루션은 개발 모드에서도 작동합니다.

내 접근 방식은 미묘하게 다릅니다.

ActiveRecord::Base.connection.tables.map{|x|x.classify.safe_constantize}.compact

classify는 문자열의 클래스 이름을 적절하게 제공 합니다. safe_constantize는 예외를 발생시키지 않고 안전하게 클래스로 바꿀 수 있도록합니다. 모델이 아닌 데이터베이스 테이블이있는 경우에 필요합니다. 열거 형의 0이 제거되도록 압축합니다.


클래스 이름 만 원하는 경우 :

ActiveRecord::Base.descendants.map {|f| puts f}

Rails 콘솔에서 실행하면됩니다. 행운을 빕니다!

편집 : @ sj26이 맞습니다. 자손을 호출하기 전에 이것을 먼저 실행해야합니다.

Rails.application.eager_load!

이것은 나를 위해 작동하는 것 같습니다 :

  Dir.glob(RAILS_ROOT + '/app/models/*.rb').each { |file| require file }
  @models = Object.subclasses_of(ActiveRecord::Base)

Rails는 모델을 사용할 때만 모델을로드하므로 Dir.glob 행은 models 디렉토리의 모든 파일을 "필요"합니다.

배열에 모델이 있으면 생각한 것을 수행 할 수 있습니다 (예 : 뷰 코드).

<% @models.each do |v| %>
  <li><%= h v.to_s %></li>
<% end %>

한 줄에 : Dir['app/models/\*.rb'].map {|f| File.basename(f, '.*').camelize.constantize }


ActiveRecord::Base.connection.tables


한 줄로 :

 ActiveRecord::Base.subclasses.map(&:name)

나는 아직 언급 할 수는 없지만 sj26 답변 이 최고 답변이어야 한다고 생각 합니다. 힌트 만 :

Rails.application.eager_load! unless Rails.configuration.cache_classes
ActiveRecord::Base.descendants

예, 모든 모델 이름을 찾을 수있는 방법은 여러 가지가 있지만 내 gem model_info에서 수행 한 작업gem에 포함 된 모든 모델을 제공합니다.

array=[], @model_array=[]
Rails.application.eager_load!
array=ActiveRecord::Base.descendants.collect{|x| x.to_s if x.table_exists?}.compact
array.each do |x|
  if  x.split('::').last.split('_').first != "HABTM"
    @model_array.push(x)
  end
  @model_array.delete('ActiveRecord::SchemaMigration')
end

그런 다음 간단히 이것을 인쇄하십시오.

@model_array

이것은 Rails 3.2.18에서 작동합니다

Rails.application.eager_load!

def all_models
  models = Dir["#{Rails.root}/app/models/**/*.rb"].map do |m|
    m.chomp('.rb').camelize.split("::").last
  end
end

모든 레일을 사전로드하지 않으려면 다음을 수행하십시오.

Dir.glob("#{Rails.root}/app/models/**/*.rb").each {|f| require_dependency(f) }

require_dependency (f)는 사용하는 것과 같습니다 Rails.application.eager_load!. 이미 필요한 파일 오류를 피해야합니다.

그런 다음 모든 종류의 솔루션을 사용하여 AR 모델을 나열 할 수 있습니다. ActiveRecord::Base.descendants


Module.constants.select { |c| (eval c).is_a?(Class) && (eval c) < ActiveRecord::Base }

다음은 복잡한 Rails 앱 (하나의 파워 스퀘어)으로 검증 된 솔루션입니다.

def all_models
  # must eager load all the classes...
  Dir.glob("#{RAILS_ROOT}/app/models/**/*.rb") do |model_path|
    begin
      require model_path
    rescue
      # ignore
    end
  end
  # simply return them
  ActiveRecord::Base.send(:subclasses)
end

이 스레드에서 답변의 가장 큰 부분을 차지하고 가장 간단하고 철저한 솔루션으로 결합합니다. 모델이 하위 디렉토리에있는 경우 set_table_name 등을 사용합니다.


@Aditya Sanghi의 의견을 바탕으로 모든 모델을 속성으로 인쇄해야하기 때문에이 모델을 발견했습니다.

ActiveRecord::Base.connection.tables.map{|x|x.classify.safe_constantize}.compact.each{ |model| print "\n\n"+model.name; model.new.attributes.each{|a,b| print "\n#{a}"}}

이것은 나를 위해 일했습니다. 위의 모든 게시물에 감사드립니다. 모든 모델의 컬렉션을 반환해야합니다.

models = []

Dir.glob("#{Rails.root}/app/models/**/*.rb") do |model_path|
  temp = model_path.split(/\/models\//)
  models.push temp.last.gsub(/\.rb$/, '').camelize.constantize rescue nil
end

Rails메소드는 메소드를 구현 descendants하지만 모델을 상속 할 필요는 없습니다. ActiveRecord::Base예를 들어, 모듈을 포함하는 클래스 ActiveModel::Model는 모델과 동일한 동작을하며 테이블에 연결되지 않습니다.

따라서 위의 동료가 말한 것을 보완하기 위해 약간의 노력으로이를 수행 할 수 있습니다.

Class루비 클래스 원숭이 패치 :

class Class
  def extends? constant
    ancestors.include?(constant) if constant != self
  end
end

models조상을 포함한 방법 은 다음과 같습니다.

이 메소드 Module.constantssymbols상수 대신에 (의 ) 컬렉션을 반환 하므로 다음 Array#select과 같은 원숭이 패치와 같이 메소드 를 대체 할 수 있습니다 Module.

class Module

  def demodulize
    splitted_trail = self.to_s.split("::")
    constant = splitted_trail.last

    const_get(constant) if defines?(constant)
  end
  private :demodulize

  def defines? constant, verbose=false
    splitted_trail = constant.split("::")
    trail_name = splitted_trail.first

    begin
      trail = const_get(trail_name) if Object.send(:const_defined?, trail_name)
      splitted_trail.slice(1, splitted_trail.length - 1).each do |constant_name|
        trail = trail.send(:const_defined?, constant_name) ? trail.const_get(constant_name) : nil
      end
      true if trail
    rescue Exception => e
      $stderr.puts "Exception recovered when trying to check if the constant \"#{constant}\" is defined: #{e}" if verbose
    end unless constant.empty?
  end

  def has_constants?
    true if constants.any?
  end

  def nestings counted=[], &block
    trail = self.to_s
    collected = []
    recursivityQueue = []

    constants.each do |const_name|
      const_name = const_name.to_s
      const_for_try = "#{trail}::#{const_name}"
      constant = const_for_try.constantize

      begin
        constant_sym = constant.to_s.to_sym
        if constant && !counted.include?(constant_sym)
          counted << constant_sym
          if (constant.is_a?(Module) || constant.is_a?(Class))
            value = block_given? ? block.call(constant) : constant
            collected << value if value

            recursivityQueue.push({
              constant: constant,
              counted: counted,
              block: block
            }) if constant.has_constants?
          end
        end
      rescue Exception
      end

    end

    recursivityQueue.each do |data|
      collected.concat data[:constant].nestings(data[:counted], &data[:block])
    end

    collected
  end

end

의 원숭이 패치 String.

class String
  def constantize
    if Module.defines?(self)
      Module.const_get self
    else
      demodulized = self.split("::").last
      Module.const_get(demodulized) if Module.defines?(demodulized)
    end
  end
end

그리고 마지막으로 모델 방법

def models
  # preload only models
  application.config.eager_load_paths = model_eager_load_paths
  application.eager_load!

  models = Module.nestings do |const|
    const if const.is_a?(Class) && const != ActiveRecord::SchemaMigration && (const.extends?(ActiveRecord::Base) || const.include?(ActiveModel::Model))
  end
end

private

  def application
    ::Rails.application
  end

  def model_eager_load_paths
    eager_load_paths = application.config.eager_load_paths.collect do |eager_load_path|
      model_paths = application.config.paths["app/models"].collect do |model_path|
        eager_load_path if Regexp.new("(#{model_path})$").match(eager_load_path)
      end
    end.flatten.compact
  end

Dir.foreach("#{Rails.root.to_s}/app/models") do |model_path|
  next unless model_path.match(/.rb$/)
  model_class = model_path.gsub(/.rb$/, '').classify.constantize
  puts model_class
end

프로젝트에있는 모든 모델 클래스가 제공됩니다.


def load_models_in_development
  if Rails.env == "development"
    load_models_for(Rails.root)
    Rails.application.railties.engines.each do |r|
      load_models_for(r.root)
    end
  end
end

def load_models_for(root)
  Dir.glob("#{root}/app/models/**/*.rb") do |model_path|
    begin
      require model_path
    rescue
      # ignore
    end
  end
end

Rails 4 에서 많은 답변을 실패했습니다. (하나님을 위해 한두 가지를 바꿨습니다) 나는 내 자신을 추가하기로 결정했습니다. ActiveRecord :: Base.connection을 호출하고 테이블 이름을 가져간 것은 효과가 있었지만 원치 않는 일부 모델 (app / models /의 폴더에 있음)을 숨겨서 원하는 결과를 얻지 못했습니다. 지우다:

def list_models
  Dir.glob("#{Rails.root}/app/models/*.rb").map{|x| x.split("/").last.split(".").first.camelize}
end

I put that in an initializer and can call it from anywhere. Prevents unnecessary mouse-usage.


can check this

@models = ActiveRecord::Base.connection.tables.collect{|t| t.underscore.singularize.camelize}

Assuming all models are in app/models and you have grep & awk on your server (majority of the cases),

# extract lines that match specific string, and print 2nd word of each line
results = `grep -r "< ActiveRecord::Base" app/models/ | awk '{print $2}'`
model_names = results.split("\n")

It it faster than Rails.application.eager_load! or looping through each file with Dir.

EDIT:

The disadvantage of this method is that it misses models that indirectly inherit from ActiveRecord (e.g. FictionalBook < Book). The surest way is Rails.application.eager_load!; ActiveRecord::Base.descendants.map(&:name), even though it's kinda slow.


I'm just throwing this example here if anyone finds it useful. Solution is based on this answer https://stackoverflow.com/a/10712838/473040.

Let say you have a column public_uid that is used as a primary ID to outside world (you can findjreasons why you would want to do that here)

이제 기존 모델에이 필드를 도입했으며 아직 설정되지 않은 모든 레코드를 재생성하려고합니다. 당신은 이렇게 할 수 있습니다

# lib/tasks/data_integirity.rake
namespace :di do
  namespace :public_uids do
    desc "Data Integrity: genereate public_uid for any model record that doesn't have value of public_uid"
    task generate: :environment do
      Rails.application.eager_load!
      ActiveRecord::Base
        .descendants
        .select {|f| f.attribute_names.include?("public_uid") }
        .each do |m| 
          m.where(public_uid: nil).each { |mi| puts "Generating public_uid for #{m}#id #{mi.id}"; mi.generate_public_uid; mi.save }
      end 
    end 
  end 
end

당신은 지금 실행할 수 있습니다 rake di:public_uids:generate

참고 URL : https://stackoverflow.com/questions/516579/is-there-a-way-to-get-a-collection-of-all-the-models-in-your-rails-app

반응형