gpt4 book ai didi

ruby-on-rails - Rails 中同一个类的多个关联的最佳实践?

转载 作者:数据小太阳 更新时间:2023-10-29 07:12:33 26 4
gpt4 key购买 nike

我认为我的问题最好用一个例子来描述。假设我有一个名为“Thing”的简单模型,它有一些简单数据类型的属性。像...

Thing
- foo:string
- goo:string
- bar:int

这并不难。数据库表将包含具有这三个属性的三列,我可以使用 @thing.foo 或 @thing.bar 之类的东西访问它们。

但我要解决的问题是当“foo”或“goo”不再包含在简单数据类型中时会发生什么?假设 foo 和 goo 代表相同类型的对象。也就是说,它们都是“Whazit”的实例,只是数据不同。所以现在事情可能看起来像这样......

Thing
- bar:int

但是现在有一个新的模型叫做“Whazit”,看起来像这样......

Whazit
- content:string
- value:int
- thing_id:int

到目前为止一切都很好。现在这是我被困的地方。如果我有@thing,我如何设置它以按名称引用我的 2 个 Whazit 实例(郑重声明,“业务规则”是任何事物总是恰好有 2 个 Whazit)?也就是说,我需要知道我拥有的 Whazit 基本上是 foo 还是 goo。显然,我不能在当前设置中执行 @thing.foo,但我认为这是理想的。

我最初的想法是向 Whazit 添加一个“名称”属性,这样我就可以获得与我的@thing 关联的 Whatzits,然后通过名称选择我想要的 Whazit。虽然这看起来很丑。

有没有更好的办法?

最佳答案

有几种方法可以做到这一点。首先,您可以设置两个 belongs_to/has_one 关系:

things
- bar:int
- foo_id:int
- goo_id:int

whazits
- content:string
- value:int

class Thing < ActiveRecord::Base
belongs_to :foo, :class_name => "whazit"
belongs_to :goo, :class_name => "whazit"
end

class Whazit < ActiveRecord::Base
has_one :foo_owner, class_name => "thing", foreign_key => "foo_id"
has_one :goo_owner, class_name => "thing", foreign_key => "goo_id"

# Perhaps some before save logic to make sure that either foo_owner
# or goo_owner are non-nil, but not both.
end

另一个更简洁的选择,但在处理插件等时也更痛苦,是单表继承。在这种情况下,您有两个类,Foo 和 Goo,但它们都保存在 whazits 表中,并使用类型列来区分它们。

things
- bar:int

whazits
- content:string
- value:int
- thing_id:int
- type:string

class Thing < ActiveRecord::Base
belongs_to :foo
belongs_to :goo
end

class Whazit < ActiveRecord::Base
# .. whatever methods they have in common ..
end

class Foo < Whazit
has_one :thing
end

class Goo < Whazit
has_one :thing
end

在这两种情况下,您都可以执行 @thing.foo@thing.goo 之类的操作。使用第一种方法,您需要执行以下操作:

@thing.foo = Whazit.new

而对于第二种方法,您可以执行以下操作:

@thing.foo = Foo.new

不过,STI 有其自身的一系列问题,尤其是当您使用较旧的插件和 gem 时。通常这是调用 @object.class 的代码的问题,而他们真正想要的是 @object.base_class。必要时打补丁很容易。

关于ruby-on-rails - Rails 中同一个类的多个关联的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/757512/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com