如何迭代哈希数据对象并将其存储在 rails 中的 SQLite 数据库中?
how can I iterate hash data object and store in SQLite database in rails?
我正在处理 JSON 数据。使用 httparty
gem 从 URL 获取 JSON 数据非常有效。现在我想迭代哈希数据对象并存储在 SQLite 数据库中。
# HTTParty response
@sett = {
"restaurant_name": "Restaurant 3",
"address": "xyz address",
"country": "United States",
"currency": "USD",
"client_key": "12345",
"client_name": "Client 3"
}
我想像这样在数据库中存储此 JSON 数据:
+-----------------+---------------+
| meta_key | meta_value |
+-----------------+---------------+
| restaurant_name | abc restatant |
| country | USA |
| ... | ... |
+-----------------+---------------+
def index
require 'httparty'
@setting = HTTParty.get(
'http://codekyt.in/froodle-wp/wp-json/data/v2/projects?client_key=12345',
headers: { 'Content-Type' => 'application/json' }
)
@sett = @setting.parsed_response
@sett.each_key do |key, value|
m = Setting.new
m.meta_data = key
m.meta_value = value
m.save
end
end
它存储但以数组的格式而不是散列的格式。
在数据库中,
t.string :meta_data
t.string :meta_value
在迁移中,添加
def change
add_column :settings, :meta_data, :json
end
或者在创建新的 table、
的情况下
t.json :meta_data # storing meta_data & meta_value in your code
在setting.rb
模型中,
serialize: :meta_data, JSON
并在您的代码中更改为,
@setting = HTTParty.get(
'http://codekyt.in/froodle-wp/wp-json/data/v2/projects?client_key=12345',
:headers =>{'Content-Type' => 'application/json'}
)
Setting.create(meta_data: @setting.parsed_response)
可以根据您的情况对上面要保存的关联对象进行一些小改动
您的代码示例中有几处错误。
当您循环遍历哈希时,您使用 Hash#each_key
。它只循环键,而不循环值。
@sett.each_key do |key, value|
# ^- will always be nil
要正确循环 key/value 对,请使用 Hash#each
.
您调用 save
in void context. What happens when a record cannot be saved? Currently it sets an error on the setting record and returns false
, but both the return value and errors are ignored. This means that if a record for some reason cannot be saved, it's simply ignored. You might want to use save!
是为了在失败时引发异常。或者,您可以处理 save
return 值。
你怎么知道哪些记录属于一起?您目前只是在保存 meta_data
和 meta_value
。当您保存来自多个请求的设置时会发生什么?
可以通过添加与其他模型的关联来解决此问题。结果代码:
request = Request.create!(url: url)
@sett.each do |key, value|
request.settings.create!(
meta_data: key,
meta_value: value
)
end
或者您可以像这样自己管理此列:
request_nr = Setting.maximum(:request_nr) || 0
request_nr += 1
@sett.each do |key, value|
Setting.create!(
request_nr: request_nr,
meta_data: key,
meta_value: value
)
end
如果上述问题得到解决,您可以通过执行以下操作将一组记录转换为散列。
# First you need to fetch the records that belong together.
Setting.where(request_nr: 1)
#=> #<ActiveRecord::Relation [#<Setting id: 1, meta_data: ...>, ...]>
# The above will result in an collection of records, however we only care
# about the key/value. We can use `pluck` to get those values.
Setting.where(request_nr: 1).pluck(:meta_data, :meta_key)
#=> [["restaurant_name", "Restaurant 3"], ["address", "xyz address"], ...]
# The above array can be converted to a hash by simply calling `to_h` on it.
Setting.where(request_nr: 1).pluck(:meta_data, :meta_key).to_h
#=> { "restaurant_name" => "Restaurant 3", "address" => "xyz address", ... }
参考文献:
我已经在答案中提供了大部分链接。然而,这里有一些在代码块中使用的方法,但在文本中没有提到。
我正在处理 JSON 数据。使用 httparty
gem 从 URL 获取 JSON 数据非常有效。现在我想迭代哈希数据对象并存储在 SQLite 数据库中。
# HTTParty response
@sett = {
"restaurant_name": "Restaurant 3",
"address": "xyz address",
"country": "United States",
"currency": "USD",
"client_key": "12345",
"client_name": "Client 3"
}
我想像这样在数据库中存储此 JSON 数据:
+-----------------+---------------+
| meta_key | meta_value |
+-----------------+---------------+
| restaurant_name | abc restatant |
| country | USA |
| ... | ... |
+-----------------+---------------+
def index
require 'httparty'
@setting = HTTParty.get(
'http://codekyt.in/froodle-wp/wp-json/data/v2/projects?client_key=12345',
headers: { 'Content-Type' => 'application/json' }
)
@sett = @setting.parsed_response
@sett.each_key do |key, value|
m = Setting.new
m.meta_data = key
m.meta_value = value
m.save
end
end
它存储但以数组的格式而不是散列的格式。
在数据库中,
t.string :meta_data
t.string :meta_value
在迁移中,添加
def change
add_column :settings, :meta_data, :json
end
或者在创建新的 table、
的情况下t.json :meta_data # storing meta_data & meta_value in your code
在setting.rb
模型中,
serialize: :meta_data, JSON
并在您的代码中更改为,
@setting = HTTParty.get(
'http://codekyt.in/froodle-wp/wp-json/data/v2/projects?client_key=12345',
:headers =>{'Content-Type' => 'application/json'}
)
Setting.create(meta_data: @setting.parsed_response)
可以根据您的情况对上面要保存的关联对象进行一些小改动
您的代码示例中有几处错误。
当您循环遍历哈希时,您使用
Hash#each_key
。它只循环键,而不循环值。@sett.each_key do |key, value| # ^- will always be nil
要正确循环 key/value 对,请使用
Hash#each
.您调用
save
in void context. What happens when a record cannot be saved? Currently it sets an error on the setting record and returnsfalse
, but both the return value and errors are ignored. This means that if a record for some reason cannot be saved, it's simply ignored. You might want to usesave!
是为了在失败时引发异常。或者,您可以处理save
return 值。你怎么知道哪些记录属于一起?您目前只是在保存
meta_data
和meta_value
。当您保存来自多个请求的设置时会发生什么?可以通过添加与其他模型的关联来解决此问题。结果代码:
request = Request.create!(url: url) @sett.each do |key, value| request.settings.create!( meta_data: key, meta_value: value ) end
或者您可以像这样自己管理此列:
request_nr = Setting.maximum(:request_nr) || 0 request_nr += 1 @sett.each do |key, value| Setting.create!( request_nr: request_nr, meta_data: key, meta_value: value ) end
如果上述问题得到解决,您可以通过执行以下操作将一组记录转换为散列。
# First you need to fetch the records that belong together.
Setting.where(request_nr: 1)
#=> #<ActiveRecord::Relation [#<Setting id: 1, meta_data: ...>, ...]>
# The above will result in an collection of records, however we only care
# about the key/value. We can use `pluck` to get those values.
Setting.where(request_nr: 1).pluck(:meta_data, :meta_key)
#=> [["restaurant_name", "Restaurant 3"], ["address", "xyz address"], ...]
# The above array can be converted to a hash by simply calling `to_h` on it.
Setting.where(request_nr: 1).pluck(:meta_data, :meta_key).to_h
#=> { "restaurant_name" => "Restaurant 3", "address" => "xyz address", ... }
参考文献:
我已经在答案中提供了大部分链接。然而,这里有一些在代码块中使用的方法,但在文本中没有提到。