我有两个模型,为简单起见,我们将它们称为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
答案 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'