可以使用变量来引用 Rails 中的表列吗?
假设我有一张要转换的表格。它的列名称为 Item1、Item2...Item25。我无法控制列名称,我正在将其转换为更好的结构。
因为命名约定有一个模式,所以我可以动态创建列名称。问题是,当我尝试使用变量作为对象键时,它会作为文字而不是变量的内容传递。
例如,这是可行的:
if !order.item1.empty?
OrderItem.create(
:item => order.item1,
:quantity => order.qty1,
:price => order.price1
)
但我不想手工制作 25 个变体,而是想做类似的事情
i = 1
while i < 25
item_ref = "item" + i.to_s
if !order.item_ref.empty?
OrderItem.create(
:item => order.item_ref,
etc...)
i += 1
end
end
,但这当然行不通。 Rails 尝试查找 order.item_ref 而不是 order.item1,因为 order.item1 不存在。
我在不同的项目中多次遇到这个问题,有什么想法吗?
Let's say I've got a table that I'm trying to convert. Its got column names Item1, Item2... Item25. I don't have control over the column names, I'm converting from this into a better structure.
Because there's a pattern to the naming convention, I can create the column names on the fly. The problem is that when I try to use my variable as an object key, it gets passed through as a literal instead of the contents of the variable.
For instance, this works:
if !order.item1.empty?
OrderItem.create(
:item => order.item1,
:quantity => order.qty1,
:price => order.price1
)
But rather than make 25 variations of that by hand, I'd like to do something like
i = 1
while i < 25
item_ref = "item" + i.to_s
if !order.item_ref.empty?
OrderItem.create(
:item => order.item_ref,
etc...)
i += 1
end
end
But of course this doesn't work. Rails tries to look up order.item_ref instead of order.item1, which doesn't exist.
I've hit this issue a couple of times on various projects, any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
order.send item_ref
;另外,使用25.times do |i|
(从 0 开始)或(1..25).each do |i|
而不是您自己的循环。order.send item_ref
; Also, use25.times do |i|
(starts at 0) or(1..25).each do |i|
rather than your own loop.我真的不鼓励您使用这种设计,但是..无论如何..您可以使用
send()
方法来完成您正在尝试的操作。如order.send("item + i.to_s")
...I really wouldn't encourage you to use this kind of design but.. anyway.. you can do what you're trying using the
send()
method. As inorder.send("item + i.to_s")
...试试这个
它适用于我的情况
try this
it works in my case