Ruby-on-rails Rails - 附加属性并添加到数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17054113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:09:09  来源:igfitidea点击:

Rails - append attributes and add to array

ruby-on-railsruby

提问by baihu

I am having a slight problem with appending data and then adding it into the array.

我在附加数据然后将其添加到数组中时遇到了一个小问题。

Here is my code

这是我的代码

@order.orderdesc ||= []

@cart.line_items.each do |item|
 @order.orderdesc += item.quantity +  "x" + item.product.title
end

I only want to add item.quantity and item.product.title. They can be accessed.

我只想添加 item.quantity 和 item.product.title。可以访问它们。

Thanks

谢谢

回答by MrYoshiji

If you want to add "stuff" in an array, the +=is not made for that. You can use the <<operator (append at the end of the array):

如果您想在数组中添加“东西”,+=则不是为此而制作的。您可以使用<<运算符(在数组末尾追加):

@order.orderdesc ||= []

@cart.line_items.each do |item|
 @order.orderdesc << item.quantity +  "x" + item.product.title
end

Or you can use .push():

或者你可以使用.push()

@order.orderdesc ||= []

@cart.line_items.each do |item|
 @order.orderdesc.push( item.quantity +  "x" + item.product.title )
end