簡體   English   中英

Ruby on Rails與傳統數據庫的無表模型關聯

[英]Ruby on Rails Tableless Model Associations with Legacy Database

我只是在學習RoR,並且正在嘗試圍繞我的舊數據庫構建模型,該模型更多地圍繞SPROC來構建,用於查詢數據。 我找到了activerecord-tableless寶石,並正在使用它來幫助構建模型。

到目前為止,我可以使基本模型正常運行:

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屬性?

您可能會遇到困難, activerecord-tableless gem實際上是針對未存儲在SQL數據庫中的信息的。

我建議您看一下https://rubygems.org/gems/rmre ,這些內容可以幫助您基於現有架構構建active_models。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM