我有以下型号:
class User < ActiveRecord::Base
has_many :subscriptions, as: :subscribable
has_many :user_to_high_school_subscriptions
has_many :high_school_subscriptions, through: :user_to_high_school_subscriptions
def all_subscriptions
self.subscriptions + self.high_school_subscriptions.subscriptions
end
end
class UserToHighSchoolSubscription < ActiveRecord::Base
belongs_to :user
belongs_to :high_school_subscription
end
class HighSchoolSubscription < ActiveRecord::Base
has_many :user_to_high_school_subscriptions
has_many :users, through: :user_to_high_school_subscriptions
has_many :subscriptions, as: :subscribable
end
class Subscription < ActiveRecord::Base
belongs_to :subscribable, polymorphic: true
end
有没有一个聪明的方法让我得到所有Subscription
的 a User
。
我试过了
u = User.first
subs = u.all_subscriptions
但这是错误的(undefined method subscriptions' for #<ActiveRecord::Relation:
)。我认为当我尝试使用has_many :subscriptions
on the时会感到窒息,HighSchoolSubscription
因为 a user
has_many :high_school_subscriptions
. (这一行:)self.high_school_subscriptions.subscriptions
。
有没有办法在 Rails 中的 has_many 上聚合 has_many?
运行轨道 3.2.1