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.
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 User
s with:
users = response.map{|h| User.new(h)}
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With