0

new ruby on rails user here. I have a question about the following few lines of code.

First example in view.

<% sailing.travelling_parties.each do |party| %>
  <% party.party_registers.each do |reg| %>
    <%= reg.user.detailed_user.first_name %>
  <% end %>
<% end %>

When I run it in the in view, i get my expected result which is multiple names printed out. When I move it to the model and change it to the following,

Second example, in model. The ** represents what I'm actually trying to accomplish in this entire example.

class Sailing < ActiveRecord::Base

...

def gather_data
 self.travelling_parties.each do |party|
  party.party_registers.each do |reg|
    reg.user.detailed_user.first_name
    ** use a variable to count loop iterations **
  end
 end
end

Second example, in View

<%= sailing.gather_data %>

This is printing out an array filled with the 'travelling_parties' I am trying to iterate over, not what I had expected at all! So, obviously it only loops once regardless of how many names are in the sailing record.

Can any shed any light on why this is happening, and how I can get it to work like the first example, without actually putting my business logic in the view?

Thanks

1 Answer 1

1

You can use Array#map, which transforms array into other array according to given block:

def gather_data
  travelling_parties.map do |party|
    party.party_registers.map do |reg|
      reg.user.detailed_user.first_name
    end
  end
end

This method returns array of arrays with first names. If you want get one-dimensional array, use flat_map instead of first map, like below:

def gather_data
  travelling_parties.flat_map do |party|
    party.party_registers.map do |reg|
      reg.user.detailed_user.first_name
    end
  end
end
Sign up to request clarification or add additional context in comments.

2 Comments

Great! This is what I was looking for, thanks. Do you know know I would be able to get my array of names, AND get the count of names without having to call <p><%= sailing.gather_data.count %></p> AND <p><%= sailing.gather_data %></p> (basically doubling my query. Thanks again!
@Aptorian, put sailing.gather_data into variable and use size instead of count on this variable

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.