baihu
baihu

Reputation: 461

Rails - append attributes and add to array

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.

Thanks

Upvotes: 23

Views: 52597

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

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():

@order.orderdesc ||= []

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

Upvotes: 37

Related Questions