所以我有这个:
User:
has_many: subscriptions
Subscription:
belongs_to: user
has_many: payments
Payment:
belongs_to: subscription
如果我有付款ID,我该如何找到用户?
答案 0 :(得分:1)
正如尼克所说,Payment.find(id).subscription.user
会很有效。如果您经常这样做,我建议您同时添加has_one :through
关系。
class Payment < ApplicationRecord
belongs_to :subscription
has_one :user, through: :subscription
end
然后你可以直接引用Payment.find(id).user
!
答案 1 :(得分:0)
如果您声明从付款到用户的间接关联,您可以直接获取:
class User < ApplicationRecord
has_many :subscriptions
has_many :payments, through: :subscriptions
end
clas Subscription < ApplicationRecord
belongs_to :user
has_many :payments
end
class Payment < ApplicationRecord
belongs_to :subscription
has_one :user, through: :subscription
end
user = User.joins(:payments).where(payments: { id: [id] }).first
# or
payment = Payment.eager_load(:user).find(id)
user = payment.user