如何区分相似的 has_many :through associations in Rails?

How to differentiate similar has_many :through associations in Rails?

我将从我的模型开始:

class Project < ApplicationRecord
  has_many :permissions
  has_many :wallets, through: :permissions

  has_many :follows
  has_many :wallets, through: :follows
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
  has_many :projects, through: :permissions

  has_many :follows
  has_many :projects, through: :follows
end

如您所见,权限和关注都是通过项目和钱包的关联。

它们有不同的用途(Permission 允许钱包访问管理项目,而 Follow 允许钱包“关注”项目以进行更新)。

那么我怎样才能区分它们呢?例如,如果我这样做 Wallet.find(1).projects,它默认使用“关注”模型……尽管在某些情况下我希望它实际使用“许可”模型。

相信您会发现它会默认为最后定义的 has_many :projects

需要给协会起不同的名字,这需要像...

class Wallet < ApplicationRecord
  has_many :permissions
  has_many :projects, through: :permissions

  has_many :follows
  has_many :follow_projects, through: :follows, source: :project
end