ruby-on-rails - 模型 A 可以拥有一个模型 B,而模型 B 则拥有多个模型 A 吗?
问题描述
这是我目前拥有的一个示例:
#app/models/company.rb
class Company < ApplicationRecord
has_one :platform
end
.
#app.models/platform.rb
class Platform < ApplicationRecord
has_and_belongs_to_many :companies
end
而且我还有一个迁移,它创建了一个连接表来将一个平台与多家公司联系起来
class CreateJoinTableCompanyPlatforms < ActiveRecord::Migration[5.1]
def change
create_join_table :companies, :platforms do |t|
t.index [:company_id, :platform_id]
t.index [:platform_id, :company_id]
end
end
end
但是,当我转到我的视图并尝试调用Company.first.platform
时,我收到此错误:
ActionView::Template::Error (Mysql2::Error: Unknown column 'platforms.company_id' in 'where子句': SELECT
platforms
.* FROMplatforms
WHEREplatforms
.company_id
= 1 LIMIT 1):
我的连接表是否有问题,或者我不能像这样构建我的模型?
如果我将其更改has_one :platform
为,has_and_belongs_to_many :platforms
那么它可以完美运行,所以我一定会遗漏一些东西,否则这可能不是最好的方法。
我使用 a 的原因has_one
是因为每次我打电话时company
,我都不想指定company.platforms.first.name
并且宁愿这样做,company.platform.name
因为它应该只有一个。
解决方案
has_and_belongs_to_many
旨在对称使用;换句话说,如果 Platform 模型用它来指向 Company,那么 Company 模型应该用它来指向 Platform。尝试将其与另一种类型的关联配对应该会失败,并且正在失败。
如果你想company.platform.name
工作,你考虑过has_many
人际关系吗?像这样:
class Company < ApplicationRecord
belongs_to :platform
end
class Platform < ApplicationRecord
has_many :companies
end
这种类型的关系不需要连接表。相反,它使用platform.company_id
错误消息中提到的列。
推荐阅读
- mysql - 从列中以逗号收集的 id 中选择行
- java - 面临问题 java xml NamespaceContext
- android - 如何在音频处理应用程序中正确恢复 MIC?
- sqlite - 如果没有运行 DBMS,什么会执行应用程序提交的 SQL 命令?
- p2p - IPFS - pubsub 从浏览器连接到对等点
- android - 向 TextView 添加效果
- google-apps-script - 如何从应用程序脚本中使用 Google 表格查询或 Google 可视化 api?
- python - 根据行数连接两个数据帧
- html - 带有纸张输入的 Polymer 1.x 插入图像
- amazon-web-services - 将 Kubernetes 流量暴露给 80 (http) 和 443 (https)