Rails 4 - How to populate user model from JSON API?

Firstly, I am new to rails, so I'm sorry if there is something that I do not understand correctly. I am wondering how I can populate a model using data mining via API.

Context: I use OAuth2 authentication with omniauth / devise.

On my client side of the client (opposite the provider), I selected all the users who logged in at least once, this is the "client application", and I want to display them. It is obvious that at any time when a new user is registered in the client application, I do not save all his information in the client database in order to avoid duplication. All I store is user_id along with its access token.

So I thought that after collecting all the user data, I could fill it in to the user model before passing it to the view. What would be the best way to do such a thing? I was looking for the Named Orb, but I don’t understand how to apply it to my specific scenario. For example, it would be great if you could populate all users of my model using something like this:

# ApiRequest is a container class for HTTParty get = ApiRequest.new.get_users(User.all) // here "get" is a JSON array of all users data response = get.parsed_response['users'] User.populate(response).all # would something like this possible? If yes, is Named Scope the appropriate solution? 

Thank you very much for your help.

+6
source share
4 answers

Let's say that response is an array of attribute hats:

 [{'id' => 1, 'name' => 'Dave'}, {'id' => 2, 'name' => 'Bill'}] 

You can map this to a User array with:

 users = response.map{|h| User.new(h)} 
+8
source

If you do not want to touch the database and also want to fill in virtual attributes, I think the only way is to implement your own populate method:

 # The User class def self.populate(data) data.map do |user_json| user = User.find(user_json[:id]) user.assign_attributes(user_json) user end end 

Refer to the assign_attributes documentation for security recommendations.

+2
source

The easiest way is to use active_resource http://railscasts.com/episodes/94-activeresource-basics

PS In Rails 4 he switched to gem https://github.com/rails/activeresource

+2
source

I have not found a direct way to do this, the shortest solution I can offer is to use the update method:

 ids = get.map{ |e| e["id"] } User.update(ids, get) 
+1
source

All Articles