In a dropdown I have fetched all controller classes with all their actions in another dropdown dynamically which are used for certain operations. There are some controllers that don't have any models like 'DashboardsController' don't have Dashboard
model. It is just used to display dashboards.
So, basically I need to filter out controllers without models. I need a method to which I pass the controller class and returns me true/false
.
def has_model?(controller_klass)
# TODO
end
You could try something like this, if you pass in the name of the controller as a string. This solution assumes that your models are using ActiveRecord
prior to rails 5 where ApplicationRecord
was used to define models; in that case just switch ActiveRecord::Base
with ApplicationRecord
. Also if you have models that are plain old ruby objects (POROs), then this wont work for them.
def has_model?(controller_klass)
begin
class_string = controller_klass.to_s.gsub('Controller', '').singularize
class_instance = class_string.constantize.new
return class_instance.class.ancestors.include? ActiveRecord::Base
rescue NameError => e
return false
end
end
This method doesn't rely on exceptions, and works with input as Class or String. It should work for any Rails version :
def has_model?(controller_klass)
all_models = ActiveRecord::Base.descendants.map(&:to_s)
model_klass_string = controller_klass.to_s.sub(/Controller$/,'').singularize
all_models.include?(model_klass_string)
end
Note : you need to set
config.eager_load = true
in
config/environments/development.rb
If you have non ActiveRecord models, you can ignore the previous note and use :
all_models = Dir[File.join(Rails.root,"app/models", "**","*.rb")].map{|f| File.basename(f,'.rb').camelize}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.