I’m making a GET call to an external source using the gem ‘httparty’; here’s my Controller.rb:
def show
response = HTTParty.get('URI')
user = JSON.parse(response)
user.each {|line| puts line['user']['id']}
#the "['user']['id']" is because of the nested JSON object that is returned after the
parse.
end
This returns the correct output in my rails console, but now the question is how do I save the [‘id’] to my db?
Currently, my User model has :id and :name; the JSON object from the external API sends :id and :name along with a bunch of other information I don’t need.
class User < ActiveRecord::Base
attr_accessor :id, :name
end
Any help is appreciated, thanks!
First, I would suggest that you create another column for the id (say
external_idor something), rather than saving it in the actualidcolumn of theUsermodel (that column is very important in ActiveRecord and you really don’t want to be setting it directly). You can validate uniqueness on that column to ensure that you don’t import the same user data into multiple separate records in the db.Once you have that column, create a class method in your
Usermodel (I’ve called minesave_data_from_api) to load the JSON data into the db:What this does:
user_data.map) which takes each JSON user andUser.new)line['user']['id'])u.save), anduin the block).users) and select only those that actually exist (were persisted) in the db (users.select(&:persisted?)). For example, if you have a uniqueness constraint onexternal_idand you try to load the db data again,u.savewill returnfalse, the record will not be (re-)created, and those results will be filtered out of the results returned from the method.This may or may not be the return value you want. Also, you probably want to add more attribute assignments (
name, etc. from the JSON data) in the block. I leave it up to you to fill in those other details.