1

我正在从 Harvest 中提取数据。这是我的两个模型和架构:

# schema
create_table "clients", :force => true do |t|
  t.string   "name"
  t.integer  "harvest_id"      
end

create_table "projects", :force => true do |t|
  t.string   "name"
  t.integer  "client_id"
  t.integer  "harvest_id"
end

# Client.rb
has_many :projects, :foreign_key => 'client_id' # not needed, I know

# Project.rb
belongs_to :client, :foreign_key => 'harvest_id'

我试图通过将 Project.client_id 与 Client.harvest_id 匹配来让项目找到他们的客户。这就是我得到的。

> Project.first.client_id
=> 187259

Project.first.client
=> nil

Client.find(187259).projects
=> []

这可能吗?谢谢!

4

3 回答 3

0

由于您belongs_to在 Project 模型中的关系是 on harvest_id,因此您必须确保harvest_id在项目对象中设置了属性。

> Project.first.harvest_id
=> ??

harvest_id如果未设置,可能会出现您的问题。

于 2010-03-10T23:09:32.977 回答
0

项目通过匹配项目来找到他们的客户。client_id到客户端。收获ID

这似乎没有意义,因为客户端和收获应该是不同的对象/记录,您无法匹配它们。

这就像“在有橙色种子的地方找到苹果”。

所以我们可能需要更多的上下文。


您通过以下方式定义了您的关系:

在项目方面,您说“它与客户通过client_id”有关,但在客户方面,您说“它与通过项目有关harvest_id

那里有差异。

因此,您似乎只是定义了不正确的映射。

不确定应该如何使用 Harvest_id,因此假设它只是关联:

# Client.rb
has_many :projects
belongs_to :harvest

# Project.rb
belongs_to :client
belongs_to :harvest

# Harvest
has_one :client
has_one :project
于 2010-03-10T23:45:00.843 回答
0

可能看起来不直观,但两种关系的 foreign_key 必须相同。假设您决定使用 Harvest_id 作为外键。它应该这样设置:

# Client.rb
has_many :projects, :foreign_key => 'harvest_id'

# Project.rb
belongs_to :client, :foreign_key => 'harvest_id'

由于客户端 has_many 项目,您也将只有项目表中的 Harvest_id 字段。

于 2010-03-11T05:47:34.790 回答