1

這可能很簡單,但我對Ruby和活動記錄頗爲陌生。CSV到DataMapper導入

我有一個數據庫的CSV轉儲,我試圖使用DataMapper導入到數據庫。我無法理解我應該在模型中定義哪種類型的關係,以便它與所定義的CSV匹配。

下面是我從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 

例如:做階段belong_to項目或者是這個的has_many關係?

+1

? (這些是2種不同的東西) – mikej 2010-06-20 18:56:13

+0

對不起,我使用的是DataMapper,但假設關係類型相似?例如一對多等 – Tom 2010-06-20 19:50:22

回答

1

我假設客戶==公司。這裏的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 

這裏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 

對於你應該做一個特殊的順序導入:

  1. ClientStaff,因爲他們可以存在獨立於所有其他型號
  2. Project,它僅取決於Client
  3. Job,取決於ProjectClient
  4. Stage,您使用的ActiveRecord或者DataMapper的取決於StaffProjectJobClient
+0

我不能夠感謝你。看起來我錯過了foreign_key的概念,並以client_client_id等很多字段結束。 – Tom 2010-06-21 12:28:39