Rails 表名字符串轉換成表的實體對象

查詢拿到一個表名,本以爲可以直接使用,發現是報錯的:

NoMethodError: undefined method `all' for "Organization":String

然後發現取到的表名是String,於是查詢變成了 "Organization".all

經過查詢發現這樣是可以的

"Organization".constantize.all

一個文檔裏面這麼寫:
https://api.rubyonrails.org/classes/String.html#method-i-constantize

  • constantize tries to find a declared constant with the name
    specified in the string. It raises a NameError when the name is not
    in CamelCase or is not initialized. See
    ActiveSupport::Inflector#constantize
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章