rails 3数组未定义的方法

时间:2012-03-07 06:23:46

标签: arrays ruby-on-rails-3 undefined

我的变量调用项目包含以下值的项目数组

[[#<Item id: 16, item_name: "Titan limited edition watch", description: "This is watch", reference_no: 21541, price: 5000, currency_type: nil, payment_type: "0", created_at: "2012-02-29 06:53:38", updated_at: "2012-02-29 06:53:38", quntity: 500, avatar_file_size: 8805, avatar_file_name: "images.jpg", avatar_content_type: "image/jpeg", avatar_updated_at: "2012-02-29 06:53:38">], [#<Item id: 25, item_name: "Titan limited edition watch", description: "this is watch", reference_no: 2, price: 5000, currency_type: nil, payment_type: "0", created_at: "2012-03-02 13:06:39", updated_at: "2012-03-02 13:06:39", quntity: 5, avatar_file_size: 8805, avatar_file_name: "images.jpg", avatar_content_type: "image/jpeg", avatar_updated_at: "2012-03-02 13:06:39">]]

我尝试像这样做一个循环

@items.each do |item|

end    

和item变量包含以下值

[#<Item id: 16, item_name: "Titan limited edition watch", description: "This is watch",     reference_no: 21541, price: 5000, currency_type: nil, payment_type: "0", created_at: "2012-    02-29 06:53:38", updated_at: "2012-02-29 06:53:38", quntity: 500, avatar_file_size: 8805, avatar_file_name: "images.jpg", avatar_content_type: "image/jpeg", avatar_updated_at: "2012-02-29 06:53:38">]

但是当我尝试跟随时给我错误

@items.each do |item|    
  item.item_name    
end    

错误是

undefined method `item_name' for #<Array:0xb6c1dffc>    

请帮帮我。 感谢。

1 个答案:

答案 0 :(得分:0)

你有一个数组数组;在循环内部,item是一个数组,而数组没有item_name方法。你需要得到数组中的项目。

@items.each do |item|
  item[0].item_name
end

你也可以flatten数组使其成为一维的:

@items.flatten.each do |item|
  item.item_name
end
相关问题