1

我有三个模型:

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;
4

1 回答 1

0

这应该这样做:

user = User.first
channels = user.groups.flat_map(&:channels).uniq
于 2013-10-10T17:22:33.260 回答