少於 1 分鐘閱讀

狀況一

  • "product"產生 Product 去new一個instance
  • 使用 constantize 把 string 轉換成 model
product_model = 'product'.camelize.constantize
new_product = product_model.new
#=> #<Product:0x007fd087727c20>...

狀況二

  • "product" 產生 Admin::Product 去 new 一個 instance

  • 要配合 const_get 使用

product_model = Admin.const_get('product'.camelize)
new_product = product_model.new
#=> #<AdminProduct:0x007fd087727c20>...

參考

  1. https://apidock.com/rails/String/constantize
  2. https://stackoverflow.com/questions/14562553/how-to-inflection-a-string-to-a-model-name-in-rails

更新時間:

留言