Rails中如何区分多个相似的has_many :through关联关系
Rails 同名has_many :through关联区分方案
你当前的问题本质是为两个不同业务的through关联设置了相同的关联名,Rails会默认使用后定义的关联覆盖先定义的,所以你调用Wallet#projects只会返回Follow关联的结果。
解决方案为给两个关联设置语义化的不同名称,同时通过source参数指定关联指向的模型,修改后的完整代码如下:
class Project < ApplicationRecord has_many :permissions # 权限关联的钱包,重命名为admin_wallets,指定source告知Rails关联指向wallet模型 has_many :admin_wallets, through: :permissions, source: :wallet has_many :follows # 关注关联的钱包,重命名为follower_wallets has_many :follower_wallets, through: :follows, source: :wallet # 可选:保留原有wallets方法默认返回关注钱包,兼容旧代码 alias_method :wallets, :follower_wallets end class Permission < ApplicationRecord belongs_to :project belongs_to :wallet end class Follow < ApplicationRecord belongs_to :project belongs_to :wallet end class Wallet < ApplicationRecord has_many :permissions # 权限关联的项目,重命名为managed_projects has_many :managed_projects, through: :permissions, source: :project has_many :follows # 关注关联的项目,重命名为followed_projects has_many :followed_projects, through: :follows, source: :project # 可选:保留原有projects方法默认返回关注项目,兼容旧代码 alias_method :projects, :followed_projects end
修改后可按业务场景调用不同关联:
- 获取钱包有权限管理的项目:
Wallet.find(1).managed_projects - 获取钱包关注的项目:
Wallet.find(1).followed_projects(或保留的默认方法Wallet.find(1).projects) - 获取项目的管理钱包:
Project.find(1).admin_wallets - 获取项目的关注者钱包:
Project.find(1).follower_wallets(或保留的默认方法Project.find(1).wallets)
内容的提问来源于stack exchange,提问作者Shpigford
相关产品推荐
相关产品推荐

