I want to know how to check if the model already exists in the project or not?
When user tries to create a model programatically using the same model name, need to check if it already exists or not?
I want to know how to check if the model already exists in the project or not?
When user tries to create a model programatically using the same model name, need to check if it already exists or not?
defined? ModelName
will return "constant" if model defined.
defined?
operator: ruby-doc.com/docs/ProgrammingRuby/html/tut_expressions.html#UG –
Girandole Since defined?
is problematic (see @Jiggneshh Gohel's comment), perhaps you can check the filenames in the models
dir.
files = Dir[Rails.root + 'app/models/*.rb']
models = files.map{ |m| File.basename(m, '.rb').camelize }
models.include? "User" => true
Another option is use exists
Return false if there is no column in the model.
© 2022 - 2024 — McMap. All rights reserved.
defined?
doesn't seem to return consistent results. Please check the code below: ` $ rails c Loading development environment (Rails 4.2.0) 2.2.1 :001 > defined?(User) => "constant" 2.2.1 :002 > defined?(AuthenticationToken) => nil 2.2.1 :003 > AuthenticationToken => AuthenticationToken (call 'AuthenticationToken.connection' to establish a connection) 2.2.1 :004 > defined?(AuthenticationToken) => "constant" 2.2.1 :005 > ` – Annul