0

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

1 Answer 1

4

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 ]
Sign up to request clarification or add additional context in comments.

6 Comments

I am doing this in UserMailer model. As need to cc emails. Added user solution in UserMailer model but it gives error "undefined method `encoding' for #<Array:0xacd0528>" for order_controller. In order_controller, UserMailer.welcome_email(current_user, @order).deliver
user2206724, can you please update the question with additional details about UserMailer/OrderController? Specifically, include the code which raises undefined method 'encoding' for #<Array:0xacd0528>
added the UserMailer and ordercontroller, the way it gives error
I guess this line is issue: :cc => ["[email protected]", "#{@foodio}"]. It is not taking care mail and foodio mails. How to make this work?
user2206724, change this :cc => ["[email protected]", "#{@foodio}"] to this :cc => ["[email protected]"] + @foodio
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.