1

I am new to ruby. I have a loop where i want to create a array:

@line_items.each do |i|
    if @line_items[0].product.user.email == i.product.user.email
        @foodio = i.product.user.email
    else
        @foodio[i] = i.product.user.email
    end
end

In above code, i am checking, whether line_items a different users.

In first part, if all line_items have same users, email will be @foodio. But if users are different, @foodio[] will store emails of all users.

How to do this? Please help!

2 Answers 2

3
   @foodio =  @line_items.map{ |ln| ln.product.try(:user).try(:email) }.compact.uniq

Iterate through items and select the user mail. Compact method to delete the nil possibility (user without product or user without email). Last, uniq method to delete duplicates.

In this option @foodio is always an array

If you have validates of presence in your models, simply:

@foodio =  @line_items.map{ |ln| ln.product.user.email }.uniq
Sign up to request clarification or add additional context in comments.

3 Comments

it gives error of undefined method `encoding' for #<Array:0xbf26b3c>
Put the code where you call encoding method, please. You are calling encoding method to an array, that's wrong. Remember in this option @foodio is an array of strings (emails)
I have put the method in controller action and passing the foodio to UserMailer. Is it wrong? I tried to put it in UserMailer model too but same error.
2

There are various ways that you could do this but its easiest to break down into steps.

Firstly you can convert the array of line_items to an array of email strings using the map method:

emails = @line_items.map { |item| item.product.user.email }

(This assumes there are no nil values in for product or user).

You may have duplicates in this list so you can de-duplicate with the uniq method:

emails = emails.uniq

or just

emails.uniq!

Then you can apply the logic about all emails being the same (because in that case the list would contain exactly one item):

@foodio = emails.count == 1 ? emails[0] : emails

See http://ruby-doc.org/core-2.0/Array.html

1 Comment

Hey tried this: emails = @ order.line_items.map { |item| item.product.user.email } emails = emails.uniq @foodio = emails.count == 1 ? emails[0] : emails. But it is giving error in encoding array error.

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.