Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if controller has a model in Rails

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 
like image 583
Arif Avatar asked Jan 27 '26 13:01

Arif


1 Answers

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 
like image 120
C dot StrifeVII Avatar answered Jan 30 '26 02:01

C dot StrifeVII



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!