You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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表中存储用户关联标识的字段是authorId
    • primary_key: 'uid' 告诉Rails,关联User时要匹配User表的uid字段(而非默认的id)
  • User模型的has_many关联:
    • foreign_key: 'authorId' 指定关联的Story表中,指向当前User的外键是authorId
    • primary_key: 'uid' 指定User表中用于关联的主键字段是uid

配置完成后,story.user可正确返回uid匹配authorId的用户,user.stories也能返回所有authorId匹配当前用户uid的故事。

内容的提问来源于stack exchange,提问作者Liz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 00:53:10