Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 — How to populate a user model from JSON API?

Firstly, I am new to rails so sorry if there is anything that I don't understand correctly. I am wondering how can I populate a model with data fetch thru an API.

Context: I am using a OAuth2 authentication with omniauth/devise.

In my User controller client-side (opposite to the provider), I fetched all users who logged in at least once is this "client app" and I want to display them. Obviously, anytime a new user logged in to the client app I don't store all his information in the client database to avoid duplicate. All I am storing is the user_id along with its access token.

Therefore, I was thinking that after fetching all users data I could populate them to a user model before passing it to the view. What would be the best way of doing such a thing? I was looking into the Named Scope but it is not clear to me how to apply it to my particular scenario. For instance, it would be great to be able to fetch an populate all users in 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 in advance for you help.

like image 719
user3099958 Avatar asked Dec 13 '13 15:12

user3099958


3 Answers

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

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

You can map this into an array of Users with:

users = response.map{|h| User.new(h)}
like image 134
pguardiario Avatar answered Sep 22 '22 21:09

pguardiario


If you don't want to touch database, and also want to populate 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

Check the assign_attributes documentation for security advices.

like image 39
fguillen Avatar answered Sep 22 '22 21:09

fguillen


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

P.S. In Rails 4 it's gone to gem https://github.com/rails/activeresource

like image 32
itsnikolay Avatar answered Sep 23 '22 21:09

itsnikolay