我假设您想创建 STI,其中 User 有很多频道,所以在 Rails 5 中您可以尝试以下操作:
class User < ApplicationRecord
has_many :user_channels
has_many :channels, through: :user_channels
has_many :facebook_channels, class_name: 'FacebookChannel', through: :user_channels
has_many :google_channels, class_name: 'GoogleChannel', through: :user_channels
end
class UserChannel < ApplicationRecord
# user_id
# channel_id
belongs_to :user
belongs_to :channel
belongs_to :facebook_channel, class_name: 'FacebookChannel', foreign_key: :channel_id, optional: true
belongs_to :google_channel, class_name: 'GoogleChannel', foreign_key: :channel_id, optional: true
end
class Channel < ApplicationRecord
# You need to have "type" column to be created for storing different chanels
has_many :user_channels
has_many :users, through: :user_channels
end
class FacebookChannel < Channel
has_many :user_channels
has_many :users, through: :user_channels
end
class GoogleChannel < Channel
has_many :user_channels
has_many :users, through: :user_channels
end
现在您可以通过current_user.facebook_channels.create(name: "My Facebook Channel") 获取所有FacebookChannel 和current_user.facebook_channels
基本上,它与普通的 has_many through 关系一样工作,具有 STI 的额外功能 - 您将子模型名称存储在 Channel 模型的 type 列中。
更新
对不起,我不知道我的建议不适用于 MongoDB。也许你可以简单地在你的channels 表中创建channel_type 列,有简单的channel belongs_to user 关系然后这样做:
current_user.channels.create(name: "My Channel Name", channel_type: "facebook")
current_user.channels.where(channel_type: "facebook")
您可以简单地执行current_user.channels,它为您提供用户的所有渠道,然后如果您需要,您可以根据channel_type 值对每条记录执行您需要的任何操作。
你甚至可以在 Channel 模型中创建一些作用域:
class Channel < ApplicationRecord
scope :facebook_channels, -> { where(channel_type: "facebook") }
end
然后你就可以做你想要的current_user.channels.facebook_channels
channel_type 列可以是字符串或整数,如果你使用枚举的话。
此外,如果您创建visit 列(例如“布尔”),您可以执行current_user.channels.where(visit: true) 或创建scope :visit_true, -> { where(visit: true) } 并执行current_user.channels.visit_true 之类的操作
你说什么?