ActiveRecord通过多个HABTM进行选择

时间:2013-10-10 16:46:00

标签: ruby-on-rails activerecord has-and-belongs-to-many

我有三种模式:

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;

1 个答案:

答案 0 :(得分:0)

这应该这样做:

user = User.first
channels = user.groups.flat_map(&:channels).uniq