我有三种模式:
class User < ActiveRecord::Base
has_and_belongs_to_many :groups
end
class Group < ActiveRecord::Base
has_and_belongs_to_many :channels
has_and_belongs_to_many :users
end
class Channel < ActiveRecord::Base
has_and_belongs_to_many :groups
end
为特定用户获取所有频道(没有重复)的最有效方法是什么?
如此有效:
SELECT DISTINCT name FROM users
JOIN groups_users ON users.id=groups_users.user_id
JOIN channels_groups ON groups_users.group_id=channels_groups.group_id
JOIN channels ON channels_groups.channel_id=channels.id;
答案 0 :(得分:0)
这应该这样做:
user = User.first
channels = user.groups.flat_map(&:channels).uniq