私はRoRを学んでいて、データをクエリするためのSPROCを中心に構築されたレガシーデータベースを中心にモデルを構築しようとしています。私はactiverecord-tableless gem を見つけ、それを使用してモデルを構築しています。
これまでのところ、基本モデルを正常に動作させることができます:
class Wine < ActiveRecord::Base
has_no_table
self.primary_key = "iWine"
column :iWine, :integer
column :Wine, :string
column :Vintage, :integer
....etc......
attr_accessible :iWine, :Wine, :Vintage, .....
has_many :labelImages
def self.find_wine(id)
r = ActiveRecord::Base.execute_procedure "sp_FetchWineVerbose", 'iWine' => id.to_i
if r.size > 0
w = Wine.new(r[0])
return w;
end
end
end
ここで、ActiveRecord の関連付けを利用して、関連するデータ (ラベル画像、他のヴィンテージなど) を追加で取得したいと思います。
class LabelImage < ActiveRecord::Base
has_no_table
column :id, :integer
column :width, :integer
column :height, :integer
column :wine_id, :integer
attr_accessible :id, :width, :height, :wine_id
after_initialize :fetch_data
belongs_to :wine
def fetch_data()
sql = <<-eos
SELECT iLabel AS id, Width AS width, Height AS height, ....
eos
r = ActiveRecord::Base.connection.select_all(sql, 'Label Image', [[wine_id,wine_id]])
if r.size > 0
self.assign_attributes(r[0])
end
end
end
これで、 と を呼び出すことができw = Wine.find_wine(1)
、w.labelImages.build
適切なデータを含む LabelImage オブジェクトが返されます。ただし、コンソールに次のメッセージも表示されます。
Could not log "sql.active_record" event. NoMethodError: undefined method `name' for 1:Fixnum
ソースコードを掘り下げてみましたが、これがどこから来ているのかわかりません。また、初期化をオーバーライドして複数の LabelImage オブジェクトの配列を返す方法もわかりません。特定のワインには多くのオブジェクトがある可能性があるためです。メソッドをオーバーライドする必要がありますbuild
か (そうであれば、どのように?)、またはオブジェクトを作成して Wine.labelImages 属性に割り当てる別の方法はありますか?