在Rails之外使用Active Record无法工作的关联

时间:2013-02-14 03:26:35

标签: ruby-on-rails ruby rails-activerecord

我在rails之外使用Active Record。我从API获取数据,返回我转换为哈希的XML。然后我将哈希传递给构建方法,最终将数据保存在mysql数据库中。当我单独使用我的两个模型时,一切都有效。我现在正在尝试使用关联。这两个模型看起来像这样:

series.rb

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, :series_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, :created_at, :updated_at

  has_many :observations

end


require_relative 'seriesgrab'
# Class that grabs data from an api and returns a hash
@series = Seriesgrab.new.getSeries ARGV[0]
@series = @series['series']
@theseries = Series.create(@series)

# @observations is a hash that I get from an api call
@observations['observation'].each do |observation|

   @the_observation = observation

   @theseries.observations.build(@the_observation)

end

observation.rb

require 'rubygems'
require 'active_record'  
require 'logger'

ActiveRecord::Base.establish_connection(  
:adapter => "mysql2",  
:host => "localhost",  
:username => "root",
:password => "**********",
:database => "fred"  
)  

class Observation < ActiveRecord::Base

  attr_accessible :date, :value

  belongs_to :series

end

当单独使用每个模型时,它们会收集数据并通过Active Record保存到数据库中。但是,当我试图在series.rb中使用该关联时,即:

@theseries.observations.build(@the_observation)

我收到以下错误:

~/Development/ruby/fred $ ruby series.rb wsecout
series.rb:81:in `block in <main>': undefined method `observations' for #   <Array:0x007f9599c48f20> (NoMethodError)
from series.rb:76:in `each'
from series.rb:76:in `<main>'

好像has_many和belongs_to方法不起作用。有什么想法吗?

0 个答案:

没有答案