問題描述
我正在使用 gem 'httparty' 對(duì)外部源進(jìn)行 GET 調(diào)用;這是我的 Controller.rb:
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
這會(huì)在我的 rails 控制臺(tái)中返回正確的輸出,但現(xiàn)在的問題是如何將 ['id'] 保存到我的數(shù)據(jù)庫中?
This returns the correct output in my rails console, but now the question is how do I save the ['id'] to my db?
目前,我的 User 模型有 :id 和 :name;來自外部 API 的 JSON 對(duì)象發(fā)送 :id 和 :name 以及一堆我不需要的其他信息.
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
感謝任何幫助,謝謝!
推薦答案
首先,我建議您為 id 創(chuàng)建另一列(例如 external_id
或其他內(nèi)容),而不是將其保存在User
模型的實(shí)際 id
列(該列在 ActiveRecord 中非常重要,您真的不想直接設(shè)置它).您可以驗(yàn)證該列的唯一性,以確保不會(huì)將相同的用戶數(shù)據(jù)導(dǎo)入到數(shù)據(jù)庫中的多個(gè)單獨(dú)記錄中.
First, I would suggest that you create another column for the id (say external_id
or something), rather than saving it in the actual id
column of the User
model (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.
擁有該列后,在您的 User
模型中創(chuàng)建一個(gè)類方法(我已將其稱為 save_data_from_api
)以將 JSON 數(shù)據(jù)加載到數(shù)據(jù)庫中:>
Once you have that column, create a class method in your User
model (I've called mine save_data_from_api
) to load the JSON data into the db:
class User < ActiveRecord::Base
# optional, but probably a good idea
validates :external_id, :uniqueness => true
def self.save_data_from_api
response = HTTParty.get('URI')
user_data = JSON.parse(response)
users = user_data.map do |line|
u = User.new
u.external_id = line['user']['id']
# set name value however you want to do that
u.save
u
end
users.select(&:persisted?)
end
end
這是做什么的:
- 將 JSON 數(shù)據(jù)映射到一個(gè)塊 ??(
user_data.map
),它接受每個(gè) JSON 用戶和
- Map the JSON data to a block (
user_data.map
) which takes each JSON user and
- 初始化一個(gè)新用戶 (
User.new
) - 為其分配 id JSON 數(shù)據(jù) (
line['user']['id']
) - 保存新用戶(
u.save
),并且 - 返回它(塊中的最后一個(gè)
u
).
- initializes a new user (
User.new
) - assigns it the id JSON data (
line['user']['id']
) - saves the new user (
u.save
), and - return its it (the last
u
in the block).
users
)并僅選擇數(shù)據(jù)庫中實(shí)際存在(被持久化)的結(jié)果 (users.select(&:persisted?)代碼>).例如,如果您對(duì) external_id
有唯一性約束,并且您嘗試再次加載 db 數(shù)據(jù),u.save
將返回 false
,不會(huì)(重新)創(chuàng)建記錄,并且這些結(jié)果將從方法返回的結(jié)果中過濾掉.
users
) and select only those that actually exist (were persisted) in the db (users.select(&:persisted?)
). For example, if you have a uniqueness constraint on external_id
and you try to load the db data again, u.save
will return false
, the record will not be (re-)created, and those results will be filtered out of the results returned from the method.這可能是也可能不是您想要的返回值.此外,您可能希望在塊中添加更多屬性分配(name
等來自 JSON 數(shù)據(jù)).我讓你來填寫其他細(xì)節(jié).
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.
這篇關(guān)于使用 Rails 將外部 JSON 保存到 DB的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!