gpt4 book ai didi

mysql - Ruby on Rails : Two Models Both Have Has/Many and Belongs_to

转载 作者:行者123 更新时间:2023-11-29 06:40:38 25 4
gpt4 key购买 nike

我最近继承了一个旧的 Rails 应用程序,它有一个名为 Package 的模型。任务之一是能够允许删除包。但是,由于 PackageStatePackage 模型的设置方式,目前这是不可能的。这是一个例子:

封装型号:

class Package < ActiveRecord::Base
belongs_to :package_state, class_name: 'PackageState', foreign_key: :package_state_id
has_many :package_states
end

以及 PackageState:

class PackageState < ActiveRecord::Base
has_many :packages, :class_name => 'Package'
end

重组的最佳方式是什么

最佳答案

您所描述的是一种单向 has_and_belong_to_many (HABTM) associationPackagePackageState 之间,如下所示:

class Package < ActiveRecord::Base
has_and_belongs_to_many :package_states
end

class PackageState < ActiveRecord::Base
has_many :packages
end

接受的答案 SO question有关单向 HABTM 关联的摘录如下:

Functionally yes, but semantically no. Using HABTM in a "one-sided" fashion will achieve exactly what you want. The name HABTM does unfortunately insinuate a reciprocal relationship that isn't always the case. Similarly, belongs_to :foo makes little intuitive sense here.

Don't get caught up in the semantics of HABTM and the other association, instead just consider where your IDs need to sit in order to query the data appropriately and efficiently. Remember, efficiency considerations should above all account for your productivity.

您还指出

that's not currently possible, due to the way the PackageState and Package models are setup

但这并不正确。没有什么可以阻止您使用 ActiveRecord 获取包对象并对其调用 destroy

您应该问自己打算如何使用这两种模型(特别是在删除包时)并确定哪种关联最有效。考虑到这是一个继承的应用程序,您可能需要处理遗留数据,但这是另一天的主题。

关于mysql - Ruby on Rails : Two Models Both Have Has/Many and Belongs_to,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51771375/

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