我將從我的模型開始:
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
如您所見,許可和關注都是通過專案和錢包的關聯。
它們有不同的用途(權限允許錢包訪問管理專案,而關注讓錢包“關注”專案進行更新)。
那么我該如何區分它們呢?例如,如果我這樣做Wallet.find(1).projects,它默認使用“跟隨”模型……盡管在某些情況下我希望它實際使用“權限”模型。
uj5u.com熱心網友回復:
相信你會發現它會默認為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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/359526.html
