具有 ActiveRecord 方法的结构对象? (Ruby on Rails)

发布于 2024-10-25 18:03:01 字数 999 浏览 2 评论 0原文

我有一组有限的对象(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白昼 2024-11-01 18:03:02

我建议阅读 上的帖子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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文