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开发者_如何学C
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?
order.send item_ref
; Also, use 25.times do |i|
(starts at 0) or (1..25).each do |i|
rather than your own loop.
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 in order.send("item + i.to_s")
...
try this it works in my case
i = 1
while i < 25
item_ref = "item" + i.to_s
unless order[item_ref].empty?
OrderItem.create :item => order.item_ref,:blah blah ...
i += 1
end
end
精彩评论