Rails使用哈希更新对象会产生未定义的方法stringify_keys

时间:2013-02-28 21:13:34

标签: ruby-on-rails ruby-on-rails-3

我有一个存储在名为的实例变量中的字段哈希:

 @series_from_fred

当我将此哈希传递给

 Serial.create(@series_from_fred) 

创建新的Serial(模型名称)'row',并且hash中的参数映射到Serial模型的行中的字段。

但是,当我尝试通过

更新现有的Serial时
 serial.update_attributes(@series_from_fred)

注意,'serial'是

的一部分
 @serial.each do |serial|

我收到以下错误:

NoMethodError in AdminsController#checkSerials

undefined method `stringify_keys' for #<Array:0x007fd1fe3085e0>

有什么想法吗?

如果我进入rails控制台并输入'Serial'

,会发生这种情况
Serial(id: integer, series_name: string, realtime_start: string, 
realtime_end: string, title: string, observation_start: string, 
observation_end: string, frequency: string, frequency_short: string, 
units: string, units_short: string, seasonal_adjustment: string, 
seasonal_adjustment_short: string, last_updated: string, popularity: string, 
notes: text, created_at: datetime, updated_at: datetime)

由于我在运行时从api获取数据,如果我进入rails控制台并键入'@series_from_fred,我将返回'nil'。但是,使用logger.info(@ series_from_fred.to_s)我能够在终端输出中“看到”@series_from_fred的值。输出结果是:

[{"realtime_start"=>"2013-02-28", "realtime_end"=>"2013-02-28", 
"title"=>"Reserve Bank Credit - Securities Held Outright", 
"observation_start"=>"1989-03-22", "observation_end"=>"2013-02-20", 
"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-22 08:32:54-06", "popularity"=>"47", "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.", "series_name"=>"WSECOUT"}] 

1 个答案:

答案 0 :(得分:0)

虽然我不确定为什么

Serial.create(@series_from_fred) worked 

serial.update_attributes(@series_from_fred) 

无效。我所做的“解决”问题的方法是将我从api获取的xml转换为哈希:

@series_from_fred = Hash.from_xml(series_responseHolder)

将此传递给:

serial.update_attributes(@series_from_fred)

成功更新了串行模型中该记录/对象/行的参数。