[英]Active Record without Rails: How to pass an Arbitrary hash to Active Record
我正在尝试将以下Hash传递给Active Record以保存:
[{
"id"=>"WSECOUT",
"realtime_start"=>"2013-02-10",
"realtime_end"=>"2013-02-10",
"title"=>"Reserve Bank Credit - Securities Held Outright",
"observation_start"=>"1989-03-22",
"observation_end"=>"2013-02-06",
"frequency"=>"Weekly, Ending Wednesday",
"frequency_short"=>"W",
"units"=>"Billions of Dollars",
"units_short"=>"Bil. of $",
"seasonal_adjustment"=>"Not Seasonally Adjusted",
"seasonal_adjustment_short"=>"NSA",
"last_updated"=>"2013-02-08 08:32:33-06",
"popularity"=>"42",
"notes"=>"The amount of securities held by Federal Reserve Banks. This quantity is the cumulative result of permanent open market operations: outright purchases or sales of securities, conducted by the Federal Reserve. Section 14 of the Federal Reserve Act defines the securities that the Federal Reserve is authorized to buy and sell."
}]
我的ruby类看起来像这样:
require 'rubygems'
require 'active_record'
require 'logger'
ActiveRecord::Base.establish_connection(
:adapter => "mysql2",
:host => "localhost",
:username => "root",
:password => "*********",
:database => "fred"
)
class Series < ActiveRecord::Base
attr_accessible :id, :realtime_start, :realtime_end, :title, :observation_start,
:observation_end, :frequency, :frequency_short, :units, :units_short,
:seasonal_adjustment, :seasonal_adjustment_short, :last_updated,
:popularity, :notes
end
require_relative 'wsecout'
@series = Wsecout.new.getSeries "wsecout"
@series = @series['series']
test = Series.create(@series)
@series变量包含Hash。 当我运行此代码时,对象的创建与mysql中的行一样,但是,字段中没有数据。 我知道我在这里错过了一步,但我无法弄清楚哪一步。 另外,我的Hash是否会出现包含id的问题,因为Active Record会创建自己的ID?
回答你的第二个问题“将那个”id“映射到一个名为:series_id的新字段”:
@series['series'][0]['series_id'] = @series['series'][0]['id']
@series['series'][0].delete('id')
或者,如果您想根据某些条件更改多个密钥,请在if条件中使用它,如下所示:
@series['series'][0].keys.each do |k|
if(k == 'id')
@series['series'][0]['series_id'] = @series['series'][0][k]
@series['series'][0].delete(k)
end
end
这将遍历散列的每个键,如果键与id
匹配,则它添加具有相同值的另一个键series_id
并删除id
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.