Ruby 3.0.1和Rails 6.1.3.2.活动记录has_many和has_one



我有一个遗留数据库/表。如何指定has_many和has_one关系的键?

家长:PRN_AUTO_KEY(是ID字段(

儿童:CHL_AUTO_KEY(是ID字段(PRN_AUTO_KEY(是外键字段(

不确定如何进行

我认为您谈论的是一般的一对多关联。例如:参考。

看看这个,它很详细。

class Author < ApplicationRecord
has_many :books, dependent: :destroy
end
class Book < ApplicationRecord
belongs_to :author
end

因此,表格结构如下所示:作者

idcol1col2
1
2
3

如上所述,对我来说,ID字段不是ID。因此我必须执行以下操作:

class Author < ApplicationRecord::Base
set_primary_key :ath_auto_key  
has_many :books, dependent: :destroy
end
class Book < ApplicationRecord::Base
set_primary_key :bks_auto_key    
belongs_to :author  
end

相关内容

最新更新