我想下面的哈希传递给活动记录保存:没有Rails的活动记录:如何将任意哈希传递给活动记录
[{
"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变量包含散列。当我运行这段代码时,该对象的创建与mysql中的行一样,但是,这些字段中没有数据。我知道我在这里错过了一步,但我无法弄清楚哪一步。另外,是否会出现包含ID的Hash问题,因为Active Record会创建它自己的ID?
如果你的第一个例子是正确的,那么@series包含一个带有一个散列的数组。尝试'@series ['series'] [0]'或其他。或者,您可以发布'puts @series ['series']。inspect'的输出。 – Wukerplank 2013-02-10 17:03:36
工作表示感谢。有关如何将Hash中的id映射到与Action Record:id不同的:id的任何想法?在这种情况下,哈希具有“WSECOUT”的“id”。有没有办法在我使用Series.create(@series)的时候将该“id”映射到一个名为:series_id的新字段? – JohnGalt 2013-02-10 17:47:36