首页 > 解决方案 > 模型 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.* FROM platformsWHERE platforms. 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因为它应该只有一个。

标签: ruby-on-rails

解决方案


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错误消息中提到的列。


推荐阅读