user2206724
user2206724

Reputation: 1365

Rails: create one dimensional array from multidimensional array

I have a multi dimensional array: @line_items

It has links with models, product and user.

I want to generate a single dimensional array from @line_items which will contain emails of user.

Something like this:

 emails = @line_items.product.user.email

But it is not working and gives error:

 undefined method `user' for #<Array:0xb1a12e74>

For single line_item it works.

 email = @line_item.product.user.email

I tried to generate array like this:

    @line_items.each do |i|
        @foodio.each do |j|
            @foodio[j] = i.product.user.email
        end
    end

But it gives

   undefined method `each' for nil:NilClass

As foodio is nil.

Can any body help here?

Thanks for reading!

UPDATE

My UserMailer model:

class UserMailer < ActionMailer::Base
  default :from => "[email protected]"

  def welcome_email(user, order)
@user = user
    @order = order
    @line_items = @order.line_items
    @foodio = @line_items.map do |line_item|
  line_item.product.user.email
end   

    mail(:to => user.email, :cc => ["[email protected]", "#{foodio}"], :subject => "Order no. #{order.id}")
   end

  end

Order Controller:

 def process_order
   @order = current_order
   @line_items = @order.line_items
    if @line_items.size > 0
         session[:order_id] = nil
         UserMailer.welcome_email(current_user, @order).deliver
    else
      render :action => "cart"
   end

 end

Upvotes: 0

Views: 1729

Answers (1)

oldhomemovie
oldhomemovie

Reputation: 15129

I think this is what you want:

array_of_emails = @line_items.map do |line_item|
  line_item.product.user.email
end

UPD. If you have truly mutidimentinal array, use Array#flatten:

my_array = [ [1,2], [3,4], [5,6] ]
my_array.flatten # => [ 1, 2, 3, 4, 5, 6 ]

Upvotes: 4

Related Questions