Is there a way to get a collection of all the Mode

2019-01-02 16:30发布

Is there a way that you can get a collection of all of the Models in your Rails app?

Basically, can I do the likes of: -

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

27条回答
倾城一夜雪
2楼-- · 2019-01-02 16:59

Just in case anyone stumbles on this one, I've got another solution, not relying on dir reading or extending the Class class...

ActiveRecord::Base.send :subclasses

This will return an array of classes. So you can then do

ActiveRecord::Base.send(:subclasses).map(&:name)
查看更多
公子世无双
3楼-- · 2019-01-02 16:59

I think @hnovick's solution is a cool one if you dont have table-less models. This solution would work in development mode as well

My approach is subtly different though -

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

classify is well supposed to give you the name of the class from a string properly. safe_constantize ensures that you can turn it into a class safely without throwing an exception. This is needed in case you have database tables which are not models. compact so that any nils in the enumeration are removed.

查看更多
爱死公子算了
4楼-- · 2019-01-02 16:59

Yes there are many ways you can find all model names but what I did in my gem model_info is , it will give you all the models even included in the gems.

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

then simply print this

@model_array
查看更多
柔情千种
5楼-- · 2019-01-02 16:59

can check this

@models = ActiveRecord::Base.connection.tables.collect{|t| t.underscore.singularize.camelize}
查看更多
其实,你不懂
6楼-- · 2019-01-02 17:02
ActiveRecord::Base.connection.tables.map do |model|
  model.capitalize.singularize.camelize
end

will return

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

Additional information If you want to call a method on the object name without model:string unknown method or variable errors use this

model.classify.constantize.attribute_names
查看更多
刘海飞了
7楼-- · 2019-01-02 17:03

I looked for ways to do this and ended up choosing this way:

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

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

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

查看更多
登录 后发表回答