Ruby on Rails:如何检查模型是否存在

10

我想知道如何检查一个项目中是否已存在该模型?

当用户尝试通过编程方式创建具有相同模型名称的模型时,需要检查它是否已经存在。

3个回答

24

defined? ModelName 如果该模型被定义,将返回“constant”。


4
"defined?" 函数似乎不能返回一致的结果。请查看下面的代码:$ 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 > - Jignesh Gohel
同意^ 看起来有些常量只有在被引用后才会被加载? - Pandem1c
这里是关于 defined? 运算符更多信息的链接:http://ruby-doc.com/docs/ProgrammingRuby/html/tut_expressions.html#UG - saudes

3

由于defined?存在问题(请参考@Jiggneshh Gohel的评论),也许您可以检查models目录中的文件名。

files = Dir[Rails.root + 'app/models/*.rb']
models = files.map{ |m| File.basename(m, '.rb').camelize }

models.include? "User" => true

0
另一个选项是使用exists
如果模型中没有列,则返回false。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接