Active record without rails: how to pass arbitrary hash to active record

I am trying to pass the following Hash record to the 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."
  }]

      

My ruby ​​class looks like this:

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)

      

The @series variable contains the hash. When I run this code, the object is created as a string in mysql, however there is no data in the fields. I know there is a step missing here, but I cannot figure out which step. Also, would there be a problem with my hash containing the ID, because Active Record creates its own ID?

+3


source to share


1 answer


Answer your second question "match that" id "to the new field: series_id":

@series['series'][0]['series_id'] = @series['series'][0]['id']
@series['series'][0].delete('id')

      

Or, if you want to change multiple keys based on some criteria, use it in an if condition as shown below:



@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

      

This will go through every key of the hash, and if the key matches id

, then it adds another key series_id

with the same value and removes id

.

+1


source







All Articles