Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I am developing a webapp with Ruby on Rails to expand the features of mite (online time-tracking app) with the help of the offical mite API. Unfortuanaly, the API can't return all projects by a specific customer id. Because of that, i am developing a workaround.

At first, i get all customers and save them in a hash. Then i iterate throug all projects and save each project object to a hash inside the customer hash.

My code looks like this:

def index
  # Mite authentication
  Mite.account = '...'
  Mite.authenticate('...','...')

  # get all customers from Mite
  @customers = Hash.new
  Mite::Customer.all.each do |customer|
    @customers[customer.id] = {:name => customer.name, :projects => Hash.new}
  end

  # get all projects from Mite
  Mite::Project.all.each do |project|
    @customers[project.customer_id][:projects] = {:project => project}
  end
end

Unfortuanaly, only the last project is saved in the ":projects" hash. But why? Adding customers works with this method too. In general, is this "the ruby way"? I'm very new to it :)

share|improve this question

closed as off topic by Jeff Vanzella, James Khoury, Paul, Brian Reichle, Corbin Sep 3 '12 at 5:36

Questions on Code Review Stack Exchange are expected to relate to code review request within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here. If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer 1

up vote 1 down vote accepted

You should save projects in array or something like it, not hash. For example

  Mite::Customer.all.each do |customer|
    @customers[customer.id] = {:name => customer.name, :projects => []} # !!!
  end

  Mite::Project.all.each do |project|
    @customers[project.customer_id][:projects] << project # !!!
  end
share|improve this answer
    
Thank you so much! :) But can you explain WHY i have to use an array and not a hash? –  Slevin Aug 30 '12 at 14:14
    
Actually you can use and array and hash (but array imho more convenient in your case). When you use hash you need unique keys for every value (but now you use not unique key :project and every time update value for this key). So if you want to use hash you need write: @customers[project.customer_id][:projects][project.id] = project –  andrykonchin Aug 30 '12 at 19:10
    
Thanks! That helps me so much :) –  Slevin Aug 30 '12 at 21:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.