Rails how to get DB column dynamically?
Fellas,
I have a database with columns named line1, line2, line3, line4, line5, line6.
I have a
x = rand(6)+1
to get the random value. Now I want the "line"+x somehow like this:
y = @variable."line"+x.to_s
And get back the data in lineX. Whats the correct formula? TX!
只需使用Object
send
方法:
y = @variable.send("line#{x}")
Assuming you have an ActiveRecord model for your database table. The following should work:
x = rand(6)+1
@record = MyModel.find(1)
y = @record["line#{x}"]
链接地址: http://www.djcxy.com/p/77068.html
上一篇: 如何在每条匹配的行上打印行号?
下一篇: Rails如何动态获取数据库列?