Rails中belongs_to/has_many关联非id外键/主键的配置问题
解决遗留数据库的Rails模型关联问题
你的问题出在关联配置时未正确指定User模型的主键字段,且has_many关联的外键设置有误,以下是修正后的配置:
修正后的Story模型
class Story < ApplicationRecord belongs_to :user, class_name: 'User', foreign_key: 'authorId', primary_key: 'uid' end
修正后的User模型
class User < ApplicationRecord devise :database_authenticatable, :registerable, :trackable, :recoverable, :rememberable, :validatable has_many :stories, class_name: "Story", foreign_key: 'authorId', primary_key: 'uid' end
配置说明
- Story模型的belongs_to关联:
foreign_key: 'authorId'明确指定Story表中存储用户关联标识的字段是authorIdprimary_key: 'uid'告诉Rails,关联User时要匹配User表的uid字段(而非默认的id)
- User模型的has_many关联:
foreign_key: 'authorId'指定关联的Story表中,指向当前User的外键是authorIdprimary_key: 'uid'指定User表中用于关联的主键字段是uid
配置完成后,story.user可正确返回uid匹配authorId的用户,user.stories也能返回所有authorId匹配当前用户uid的故事。
内容的提问来源于stack exchange,提问作者Liz
相关产品推荐
相关产品推荐

