具有 ActiveRecord 方法的结构对象? (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 方法等,而无需访问数据库。非常感谢您的帮助。
I have a limited set of objects (20 - 30) which I need to be able to combine with ActiveRecord Objects. Putting them into the DB just seems awful because I already have two other join models hooked up to the model.
So let's say i have a class
class Thing < ActiveRecord::Base
has_many :other_things, :class_name => 'OtherThing'
end
with an existing table. How would I be able to combine this with a class not inheriting from ActiveRecord (here's my best guess)
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
Point being that I want to use ActiveRecord methods and so on without ever hitting the db. Help is greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议阅读 上的帖子Yehuda Katz 的“让任何 Ruby 对象都感觉像一个活动记录”。它介绍了如何在没有数据库支持的情况下将任何对象转换为类似模型的类。
祝你好运!
I'd suggest reading the post on "Make any Ruby Object Feel Like An Active Record" by Yehuda Katz. It goes over how to convert any object into a model-like class, without the database backing.
Good Luck!