【问题标题】:How do I collect all the topics that are owned by the members of the groups I am a member of?如何收集我所属的群组成员拥有的所有主题?
【发布时间】:2013-03-28 20:07:04
【问题描述】:

这对我来说可能很难解释,所以如果不清楚,请告诉我,以便我可以根据需要进行编辑!

我有以下例子:

class User < ActiveRecord::Base
  has_many :topics
  has_many :memberships
end

class Topic < ActiveRecord::Base
  belongs_to :user
end

#join model between User and Group
class Membership < ActiveRecord::Base
  belongs_to :user
  belongs_to :group
end

class Group < ActiveRecord::Base
  has_many :memberships
  has_many :members, :through => :memberships, :source => :user
  has_many :topics, :through => :members
end

我遇到的问题是,我正在尝试为我所属的组的所有成员所拥有的所有主题创建一个提要 (@feed_topics),而且我有点开车坚果。

我应该尝试使用关联来实现这一点,还是在我的用户模型中创建一个具有一些 ActiveRecord/SQL 的实例方法来将所有组成员的主题合并到一个 ActiveRecord::Relation 对象中?

我的目标是在控制器的操作中写入current_user.feed_topics

【问题讨论】:

  • 嗨,你能澄清一下 GroupUser 应该代表什么吗?一个用户有很多组用户是什么意思?
  • 嗨@Rebitzele,我编辑了我的问题以澄清。虽然我在这里 - GroupUser 基本上是一个会员对象,将各种用户与各种组连接起来。您现在可能可以自己回答第二个问题 :) 希望对您有所帮助。感谢您的关注。

标签: ruby-on-rails model-associations ruby-on-rails-4


【解决方案1】:

抱歉没有早点解释!我们的想法是利用“嵌套 has_many_through”来访问您的提要主题。这个概念记录在标题“嵌套关联”下:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html。 让我知道这是否仍然不清楚(或者如果它不起作用)。

class User < ActiveRecord::Base
  has_many :topics
  has_many :memberships
  has_many :groups, :through => :membership
  has_many :group_members, :through => :groups, :source => :member
  has_many :feed_topics, :through => :group_members, :source => :topic
end

【讨论】:

  • 我不清楚你想在那里做什么。我想我需要更多的解释。我将调整 GroupUsers 模型,它现在只是将其称为 Memberships 以使其更简单。希望目前没有人正在研究答案!
  • 我明白我在哪里有点困惑。我想知道你为什么在 User 模型中有has_many :group_members, :through =&gt; :groups, :source =&gt; :member,但我不怪你!也许它可以双向发挥作用。为了便于理解,我把它放在 Group 模型 b/c 中,我觉得这样做很有意义 @group.members
【解决方案2】:

到目前为止,这些是原始问题中模型的最终版本(主题和成员资格没有改变):

class User < ActiveRecord::Base
  has_many :topics
  has_many :memberships
  has_many :groups, :through => :memberships
  has_many :feed_topics, :through => :groups, :source => :member_topics
end

class Group < ActiveRecord::Base
  has_many :memberships
  has_many :members, :through => :memberships, :source => :user
  has_many :member_topics, :through => :members, :source => :topics
end

我现在正在通过添加更多组和成员来测试它是否会拉入其他组的所有其他成员的主题。

编辑:似乎一切正常。

EDIT2:我遇到的一个小问题是看到重复的主题,因为一个成员在多个组中。我了解了:uniq =&gt; true,它拯救了这一天。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多