has_many关联不返回记录,belongs_to返回不同的记录

时间:2018-10-13 14:50:09

标签: ruby-on-rails ruby-on-rails-5 associations

我有两个模型,为简单起见,我们将它们称为project模型和file模型。 除其他外,项目具有uuid:string属性。

我正在这样宣布我的联系

file.rb:
belongs_to :project, class_name: 'Project', foreign_key: 'uuid'

project.rb:
has_many     :files, class_name: 'File', dependent: :destroy

当我打电话给file.project时,我得到了另一个uuid项目返回(其中id相当于uuid.to_i

如果我在任一.files中调用project,我将得到一个空数组

示例:

p = Project.last
=> id: 7, uuid: "1abc"

f = File.create(uuid: p.uuid)
f.project
=> id: 1, uuid: "some other uuid"

p.files
=> []
f.project.files
=> []

"1abc".to_i返回1,我知道这就是为什么我得到project的ID 1,但是我需要project ID 7的原因。

生成关联时的SQL输出:

project = Project.last
=> {id: 8, uuid: 'something'}
file = File.create(uuid: project.uuid)
(5.1ms)  BEGIN

  Project Load (0.4ms)  SELECT  "projects".* FROM "projects" WHERE "projects"."id" = $1 LIMIT $2  [["id", 0], ["LIMIT", 1]]
[i18n-debug] es-CL.activerecord.models.file => nil
[i18n-debug] es-CL.activerecord.attributes.file.project => nil
[i18n-debug] es-CL.attributes.project => nil
[i18n-debug] es-CL.activerecord.errors.models.file.attributes.project.required => nil
[i18n-debug] es-CL.activerecord.errors.models.file.required => nil
[i18n-debug] es-CL.activerecord.errors.messages.required => nil
[i18n-debug] es-CL.errors.attributes.project.required => nil
[i18n-debug] es-CL.errors.messages.required => nil

1 个答案:

答案 0 :(得分:1)

通过在两个模型中添加primary_key 'uuid'foreign_key:'uuid'来解决,如下所示:

file.rb:
belongs_to :project, class_name: 'Project', foreign_key: 'uuid', primary_key: 'uuid'

project.rb:
has_many     :files, class_name: 'File', dependent: :destroy, foreign_key: 'uuid', primary_key: 'uuid'