Ruby on Rails: How to check if the Model Exists
Asked Answered
P

3

10

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?

Plated answered 3/8, 2012 at 10:25 Comment(0)
D
24

defined? ModelName will return "constant" if model defined.

Doughboy answered 3/8, 2012 at 10:29 Comment(3)
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
Agree^ it seems that some constants are only loaded after referenced?Spieler
Here's a link to more info on the defined? operator: ruby-doc.com/docs/ProgrammingRuby/html/tut_expressions.html#UGGirandole
I
3

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
Induct answered 6/6, 2016 at 12:5 Comment(0)
N
0

Another option is use exists

Return false if there is no column in the model.

Nakisha answered 22/6, 2020 at 20:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.