Girish Kumar K
Girish Kumar K

Reputation: 135

Ruby on Rails: How to check if the Model Exists

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?

Upvotes: 10

Views: 9796

Answers (3)

Cristian Canales
Cristian Canales

Reputation: 47

Another option is use exists

Return false if there is no column in the model.

Upvotes: 0

dimid
dimid

Reputation: 7631

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

Upvotes: 3

Mikhail Nikalyukin
Mikhail Nikalyukin

Reputation: 11967

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

Upvotes: 24

Related Questions