JohnGalt
JohnGalt

Reputation: 2881

Active Record without Rails: How to pass an Arbitrary hash to Active Record

I'm trying to pass the following Hash to Active Record to save:

[{
  "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 is the row in mysql, however, there is no data in the fields. I know I'm missing a step here, but I am unable to figure out which step. Also, is there going to be a problem with my Hash containing an id, because Active Record creates it's own id?

Upvotes: 3

Views: 667

Answers (1)

Manoj Monga
Manoj Monga

Reputation: 3083

Answer to your second question "map that "id" to a new field called :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, then use it in the if condition as 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 iterate through each key of the hash and if the key matches to id then it add another key series_id with the same value and delete the id.

Upvotes: 1

Related Questions