0

これは私が説明するのが難しいかもしれないので、明確でない場合はお知らせください。必要に応じて編集できます。

次の例があります。

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メンバーであるグループのすべてのメンバーが所有するすべてのトピックのフィード ( ) を作成しようとしていて、少し頭がおかしくなっていることです。

アソシエーションを使用してこれを実現しようとするか、すべてのグループのメンバーのトピックを 1 つの ActiveRecord::Relation オブジェクトに統合する ActiveRecord/SQL を持つインスタンス メソッドを User モデルに作成する必要がありますか?

私の目標はcurrent_user.feed_topics、コントローラーのアクションに書き込むことです。

4

2 に答える 2

1

これまでのところ、これらは元の質問からのモデルの最終バージョンです (トピックとメンバーシップは変更されていません)。

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 => true、その日を救いました。

于 2013-03-28T23:21:51.777 に答える
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
于 2013-03-28T21:42:01.127 に答える