【问题标题】:CSV to DataMapper ImportCSV 到 DataMapper 导入
【发布时间】:2010-06-20 17:10:53
【问题描述】:

这可能很简单,但我对 ruby​​ 和活动记录还很陌生。

我有一个数据库的 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

例如:阶段是属于_to项目还是这个has_many关系?

【问题讨论】:

  • 您使用的是 ActiveRecord 还是 DataMapper? (这是两个不同的东西)
  • 对不起,我使用的是DataMapper,但假设关系类型相似?例如一对多等

标签: ruby database-design activerecord datamapper relational-database


【解决方案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,取决于 StaffProjectJobClient

【讨论】:

  • 感激不尽。看起来我错过了foreign_key的概念,最终得到了很多像client_client_id这样的字段。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-17
  • 2015-05-23
  • 2014-05-15
  • 2017-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多