[Rails] 從string取得model
狀況一
- 由
"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>...
參考
- https://apidock.com/rails/String/constantize
- https://stackoverflow.com/questions/14562553/how-to-inflection-a-string-to-a-model-name-in-rails
留言