У меня есть две модели, назовем их 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
с идентификатором 1, но мне нужно project
идентификатор 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