user1899082
user1899082

Reputation:

What is the Ruby Structure to model a One-to-Many table?

I have an Organization table with fields like:

id
name
time_zone

and then I have a couple of other tables like Doctors with fields like:

id
organization_id  #foreign_key to Organization
name
salary

How can I model this with Ruby? Is it with Arrays? Hashes? Maps?

I am not very familiar with Ruby yet so not sure what do we have for this in Ruby? For example if it was flat, I could maybe use a simple array, but how about this structure? I want to be able to access and loop through the hierarchy later too.

Upvotes: 1

Views: 143

Answers (1)

mind.blank
mind.blank

Reputation: 4880

class Organization < ActiveRecord::Base
  has_many :doctors
end

class Doctor < ActiveRecord::Base
  belongs_to :organization
end

Make sure you have organization_id like you wrote and then you can do (just as an example):

@doctor = Doctor.first
@doctor.organization

@organization = Organization.first
@organization.doctors

Update

Can't you populate the database with something like:

Doctor.where(name: "Frank", specialization: "Rubber Duck Surgery").first_or_create

Haven't tried this, but it's probably easier than looping through complex arrays:

@organization = Organization.where(name: "Surgeons").first_or_initialize
["Bob", "Frank", "Harry"].each do |name|
  @organization.doctors.where(name: name).first_or_initialize
end
@organization.save

Update

Ok, how about the following:

@doctor_names = ["Bob", "Rob", "Fred", "Bill"]
@doctor_salaries = [10000, 15000, 30000, 400]

def return_array_of_hashes(*data)
  array = []
  data[1].each_with_index do |d, i|
    hash = {}
    (0...data.count).to_a.in_groups_of(2).each do |a,b|
      hash.merge!({data[a] => data[b][i]})
    end
    array << hash
  end
  array
end

@doctors_array = return_array_of_hashes("name", @doctor_names, "salary", @doctor_salaries)
# => [{"name"=>"Bob", "salary"=>10000}, {"name"=>"Rob", "salary"=>15000}, {"name"=>"Fred", "salary"=>30000}, {"name"=>"Bill", "salary"=>400}]

@doctors_array.each do |hash|
  Doctor.where(hash).find_or_create
end

This way you could use the same method for any model you're creating and can easily add more data to the arrays. Just make sure you add the data in the correct order of key then value.

You might need to add a check that all arrays are of the same size, although your model validations will probably discard any invalid data.

Upvotes: 1

Related Questions