Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - append attributes and add to array

Tags:

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

like image 403
baihu Avatar asked Jun 11 '13 21:06

baihu


1 Answers

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 
  • Documentation: http://apidock.com/ruby/Array/push
like image 105
MrYoshiji Avatar answered Sep 21 '22 18:09

MrYoshiji