我发现很难理解代码库中定义的一些关联.

class Patient < ApplicationRecord   
    belongs_to :g_district, class_name: "District", primary_key: "id", foreign_key: 'district_id', optional: true
    belongs_to :g_perm_district, class_name: "District", primary_key: "id", foreign_key: 'permanent_district_id', optional: true
    belongs_to :g_workplc_district, class_name: "District", primary_key: "id", foreign_key: 'workplace_district_id', optional: true    
end
class District
    belongs_to :province #, optional: true
    belongs_to :division, optional: true
    has_many :hospitals
    has_many :tehsils
    has_many :ucs
    has_many :mobile_users
    has_many :labs
    has_many :insecticides
end

我没有明确地定义她的这些类型的关联.(AS_TO:G_REDICATION,CLASS_NAME:"REGRED",PRIMARY_KEY:"id",FORENT_KEY:‘REDICATION_ID’,OPTIONAL:TRUE).

在我的代码中,没有像g_Region、g_perm_Region、g_workplc_Region这样的模型.

推荐答案

您的代码正在以不同的名称关联相同的模型.如果有疑问,您总是可以通过查看引用实际类名的class_name: "District"来进行判断.

在您的例子中,Patient可以与三个不同的地区相关联(但它们都指向地区模式):

3.times { District.create }
patient = Patient.create(
  g_district: District.find(1), 
  g_perm_district: District.find(2),
  g_workplc_district: District.find(3)
)

patient.g_district #=> #<District:0x00000001083ce048 id: 1,.. >
patient.g_perm_district #=> #<District:0x00000001083ce048 id: 2,.. >
patient.g_workplc_district #=> #<District:0x00000001083ce048 id: 3,.. >

判断Patient的迁移或模式可能也是值得的. 架构表可能如下所示:

create_table "patients", force: :cascade do |t|
    t.integer "district_id"
    t.integer "permanent_district_id"
    t.integer "workplace_district_id"
    (...other columns here...)
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
end

以及迁移:

class CreatePatients < ActiveRecord::Migration[7.0]
  def change
    create_table :patients do |t|
      t.integer :district_id
      t.integer :permanent_district_id
      t.integer :workplace_district_id
      (...other columns here...)

      t.timestamps
    end
  end
end

foreign_key: 'district_id'部分(以及另外两个)建议这些列必须存在,并帮助ActiveRecord多次正确地关联同一模型

Ruby-on-rails相关问答推荐

Rails HotWire和View Components:涡轮框架不会取代内容

对Rails进行枚举不允许空值

使用Rails和RSpec,有没有办法查看操作真正将您带到哪个页面?

如何使用 Rails 语义记录器记录整个请求(标头、正文等)

Ruby Hash 中 tap / delete 和 except 的区别

select2 未应用于所有下拉列表;它只适用于数据的最后一条记录

Rails - 如何从 http://example.com 重定向到 https://www.example.com

ActiveRecord 回调列表

Rspec:测试实例变量的赋值

FactoryGirl 和 Rspec 测试中 attributes_for 的含义

带有 master.key 的 Rails 5.2 - Heroku 部署

在 factory_girl 中填充与 children 的关联

Ruby gem 命名约定

rails回形针和乘客`'识别'命令无法识别`

在 Rails 中复制模型实例

连接表的最佳 SQL 索引

Ruby - 合并两个数组并删除重复的值

设计/Rails - 如何删除特定的 Flash 消息? (登录成功)

Test::Unit Rails - 如何断言一个数字大于另一个?

我怎样才能看到水豚在失败的黄瓜步骤中发现了什么?