我从数据库中收到所有列表。
#<ActiveRecord::Relation [#<Item id: 1, name: "AAA", unit_price: 10000><#Item ....]
接下来,我需要通过循环或迭代器将 unit_price 值除以 100,将结果写回并显示在视图中。
我这样尝试:
def index
@items = Item.all
@items.each{
@items[unit_price] = @items[unit_price] /100
}
end
作为回应,我得到:
未定义的局部变量或方法“unit_price”
我查看哈希手册
user = {name:"Vasya", last_name: "Petrov", age: 20}
user[:name] #=> "Vasya"
我这样尝试:
def index
@items = Item.all
@items.each{
@items[:unit_price] = @items[:unit_price] /100
}
end
我得到一个答案
没有将 Symbol 隐式转换为 Integer
可能 @items[:unit_price] 值不算整数,虽然它在数据库中是这样,好吧......
def index
@items = Item.all
@items.each{
@items[:unit_price] = @items[:unit_price].to_i /100
}
end
我得到一个答案
没有将 Symbol 隐式转换为 Integer
所以@items.unit_price也试过了,没有unit_price这个方法
如何遍历这些数组以及如何访问所需的字段?
您不需要更改集合中的值。您需要在输出时使用正确的
helper和partial。创建partial(_item.html.erb) 以显示一个元素并在其中使用类似这样的内容helper:在主视图中
最好的选择是使用 gem draper或keynote
有必要翻过皮肤元素
更新的答案!