Ruby on rails 我怎样才能让外键在这个简单的关系中工作?

Ruby on rails 我怎样才能让外键在这个简单的关系中工作?,ruby-on-rails,activerecord,foreign-key-relationship,Ruby On Rails,Activerecord,Foreign Key Relationship,我正在从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.intege

我正在从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\u id和client.harvest\u id来找到他们的客户。以下是我得到的结果

> Project.first.client_id
=> 187259

Project.first.client
=> nil

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

这可能吗?谢谢

由于项目模型中的
属于
关系处于
harvest\u id
状态,因此必须确保在项目对象中设置
harvest\u id
属性

> Project.first.harvest_id
=> ??
如果未设置
harvest\u id
,则可能会出现问题

项目通过匹配项目来找到其客户。客户id到客户。收获id

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

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

所以我们可能需要更多的背景


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

在项目端,您说“它通过
客户id
与客户相关”,但在客户端,您说“它通过
收获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

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

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

# Project.rb
belongs_to :client, :foreign_key => 'harvest_id'
由于客户机有许多项目,因此在projects表中也只有harvest_id字段