Search code examples
ruby-on-railsassociations

Custom Association in rails


I am finding it hard to understand some of the association defined in the code base.

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

I am not clearly getting these kind of associations defined her.(belongs_to :g_district, class_name: "District", primary_key: "id", foreign_key: 'district_id', optional: true).

In my code, there are no models like g_district, g_perm_district, g_workplc_district.


Solution

  • Sure.

    belongs_to :lab,          # instances will belong to one `lab`
      class_name: "Hospital", # but the model is not called `Lab` but `Hospital`
      primary_key: "id",      # primary key is `hospitals.id` (actually not needed)
      foreign_key: 'lab_id',  # the foreign key is `lab_id` (again not needed)
      optional: true          # okay when there is no lab assign (default: required)