0

I would like to combine data retrieved from an API with local database data in a new JSON. But I think I'm doing this wrong. Here is my code :

@data = ActiveSupport::JSON.decode(@api_data)
@data.each do |key|
  if key['state'] == "active"
    user_id = key['id']
    user_database = User.where(:user_id => user_id).take
    @userlist = []
    unless user_database.blank?
      user_data = {
        :user_id => key['id'],
        :enrolement_start_date => key['start_at'],
        :enrolement_end_date => key['end_at'],
        :user_interest => user_database.interests,
        :user_discipline_id => user_database.discipline_id,
      }
      @userlist.push(user_data)
    end
  end
end
@userlist = @userlist.to_json

Actually, it's working but I only receive the last user as result. I don't figure how to make it works :-/ Many thanks in advance !

5
  • Where is @courselist defined, is it supposed to be there? Commented Aug 6, 2013 at 22:33
  • Corrected, It's a simple example from a more longer one ;) Sorry Commented Aug 6, 2013 at 22:43
  • You should be getting an error where you're calling take because take requires one parameter. Check the value of user_database after that call. Commented Aug 6, 2013 at 22:46
  • Also these lines should probably be like: :user_id => key['id'], and the other two lines after it, notice the rocket notation. Commented Aug 6, 2013 at 22:52
  • You right, It's like that in my code, I'll edit it, sorry it's late here :) The user_database returns me an object #<User:0x000000037e1820> Commented Aug 6, 2013 at 22:57

1 Answer 1

1
@userlist = []

that line, each time through the loop

@data.each do |key|

is clearing out the previous data by re-initializing @userlist. Then you're returning the user you added last, since all the others were thrown away the last time you assigned an empty array to @userlist.

Just move

@userlist = []

above

@data.each do |key|

and you should be good.

Sign up to request clarification or add additional context in comments.

Comments

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.