[英]Struct Objects with ActiveRecord methods? (Ruby on Rails)
我只有一組有限的對象(20-30),可以與ActiveRecord對象結合使用。 將它們放入數據庫似乎很糟糕,因為我已經將另外兩個連接模型連接到該模型。
假設我有一堂課
class Thing < ActiveRecord::Base
has_many :other_things, :class_name => 'OtherThing'
end
與現有表。 如何將其與不繼承自ActiveRecord的類結合起來(這是我的最佳猜測)
class OtherThing < ActiveRecord::Base
OtherThing = Struct.new(:id, :name, :age, :monkey_fighting_ability)
belongs_to :thing, :class_name => 'Thing'
validate :something
def self.search_for(something)
MY_GLOBAL_HASH[something].map do |hash|
instance = OtherThing.new
hash.each_pair do |k,v|
instance.send(:"#{k}=", v)
end
instance
end
end
#if AR wants to call save
def save
return true
end
alias save save!
protected
def something
self.errors.add(:monkey_fighting_ability, 'must be unlimited') if self.class.search_for(something).empty?
end
end
關鍵是我想使用ActiveRecord方法等等,而無需訪問數據庫。 非常感謝您的幫助。
我建議閱讀由Yehuda Katz撰寫的“使任何Ruby對象感覺像一個活動記錄”一文 。 它討論了如何在沒有數據庫支持的情況下將任何對象轉換為類似模型的類。
祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.