[英]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.