raghu palakodety
raghu palakodety

Reputation: 1

Unable to model data as a tree in rails

I am trying to build a tree with the following models and schema respectively

a)

class RecruitmentPhase < ApplicationRecord
  belongs_to :cohort, optional: true
  belongs_to :parent, class_name: 'Cohort', required: false , dependent: :destroy
  has_many :disease_phaseid_questionnaires, dependent: :destroy, foreign_key: :phase_id
  def phase_name_ret
    phase_name
  end
end
  create_table "recruitment_phases", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci", force: :cascade do |t|
    t.integer "phase_id"
    t.string "phase_token"
    t.string "phase_name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "parent_id"
  end

b)

class Cohort < ApplicationRecord
end
  create_table "cohorts", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci", force: :cascade do |t|
    t.string "disease_code_id"
    t.string "disease_name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.bigint "patient_id"
    t.integer "recruitment_phase_ids"
    t.index ["patient_id"], name: "index_cohorts_on_patient_id"
  end

c)

class Source < ApplicationRecord
  belongs_to :recruitment_phase, class_name: 'recruitment_phase', foreign_key: 'recruitment_phase_id'
end
  create_table "sources", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci", force: :cascade do |t|
    t.integer "source_id"
    t.string "source_token"
    t.string "source_name"
    t.string "description"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

I would like to model the data as follows using closure tree but failed to do so as they are multiple models with different data members. Can anyone let me know how I can approach this problem?

Cohort
  |_____RecruitmentPhase
           |_______________Source

Upvotes: 0

Views: 40

Answers (1)

Divyaraj Solanki
Divyaraj Solanki

Reputation: 342

Migrations

rails generate model Cohort
rails generate model RecruitmentPhase cohort:references
rails generate model Source recruitment_phase:references

Models

# app/models/cohort.rb
has_many :recruitment_phases
has_many :sources, through: :recruitment_phases

# app/models/recruitment_phase.rb
belongs_to :cohort
has_many :sources

# app/models/sources.rb
belongs_to :recruitment_phase
has_one :cohort, through: :recruitment_phase

Upvotes: 1

Related Questions