views:

40

answers:

1

This is probably very simple, but I'm quite new to ruby and active record.

I've got a CSV dump of a database which I'm trying to import to a database using DataMapper. I'm having trouble understanding which type of relationships I should define in the models so that it matches what is defined CSV.

Here's what data I've got from the CSV:

Stages:
id
staff_id
project_id
job_id
company_id

Projects:
id
company_id

Jobs:
id
project_id
company_id

Client:
id

Staff:
id

For example: do stages belong_to projects or is this has_many relationship?

+1  A: 

I'm assuming client == company. Here an example for ActiveRecord

class Stage < ActiveRecord::Base
  belongs_to :staff
  belongs_to :project
  belongs_to :job
  belongs_to :company, :class => "Client"
end

class Project < ActiveRecord::Base
  belongs_to :company, :class => "Client"
  has_many :stages
end

class Job < ActiveRecord::Base
  belongs_to :project
  belongs_to :company, :class => "Client"
  has_many :stages
end

class Client < ActiveRecord::Base
  has_many :jobs, :foreign_key => "company_id"
  has_many :projects, :foreign_key => "company_id"
  has_many :stages, :foreign_key => "company_id"
end

class Staff < ActiveRecord::Base
  has_many :stages
end

Here an example for DataMapper:

class Stage
  include DataMapper::Resource
  property :id, Serial
  belongs_to :staff
  belongs_to :project
  belongs_to :job
  belongs_to :company, "Client"
end

class Project
  include DataMapper::Resource
  property :id, Serial
  belongs_to :company, "Client"
  has n, :stages
end

class Job
  include DataMapper::Resource
  property :id, Serial
  belongs_to :project
  belongs_to :company, "Client"
  has n, :stages
end

class Client
  include DataMapper::Resource
  property :id, Serial
  has n, :jobs, :foreign_key => "company_id"
  has n, :projects, :foreign_key => "company_id"
  has n, :stages, :foreign_key => "company_id"
end

class Staff
  include DataMapper::Resource
  property :id, Serial
  has n, :stages
end

For the import you should do it in a special order:

  1. Client, Staff, because they can exist independent of all other models
  2. Project, it depends only on Client
  3. Job, depends on Project and Client
  4. Stage, depends on Staff, Project, Job and Client
jigfox
@Jens I can't thank you enough. Looks like I was missing the concept of foreign_key and ended up with lots of fields like client_client_id.
Tom