如何通过 Rails 中的关联来区分类似的 has_many :?

Shp*_*ord 1 model ruby-on-rails associations

我将从我的模型开始:

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
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,权限和关注都是通过项目和钱包的关联来实现的。

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

那么我该如何区分它们呢?例如,如果我这样做Wallet.find(1).projects,它默认使用“Follow”模型......尽管在某些情况下我希望它实际上使用“Permission”模型。

dbu*_*ger 6

相信您会发现它会默认为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
Run Code Online (Sandbox Code Playgroud)