Podwójne has_many :through

Mam taki maly problem:

Sa 3 modele:

  • User
  • Group
  • News

User

  • has_and_belongs_to_many :groups

Group

  • has_and_belongs_to_many :users
  • has_and_belongs_to_many :news

News

  • has_and_belongs_to_many :groups

Jak teraz zrobic aby User

  • has_many :news, :through => :grups

Nie mozna zrobic :through dla habtm.

Nie twierdze na 100%, ze sie nie da, ale ja tego nie widze.

Ja bym chyba tak sie do tego zabral (nie twierdze, ze zadziala)

[code]class User < AR
has_many: memberships;
has_many: groups, :through => memberships
end
class Membership < AR
belongs_to :user
belongs_to :group
end
class Group < AR
has_many :memberships
has_many :users, :through => :memberships
has_many :subscriptions
has_many :news_pieces, :through => :subscriptions
end
class Subscription
belongs_to :news_piece
belongs_to :group
end
class NewsPiece
has_many :subscriptions
has_many :groups, :through => :subscriptions
end

Subscription.find(:all, :conditions => [“group_id in (?)”, user.group_ids], :include => :news_piece)

Acha group_ids nie zadziala, trzeba sobie dopisac:

User < AR
def group_ids
self.groups.map(&:id)
end
end[/code]
Albo cos w tym stylu.

W sumie to mozna to sobie zamknac w Userze

User < AR def news_pieces subs = Subscription.find(:all, :conditions => ["group_id in (?)", user.group_ids], :include => :news_piece) subs.inject([]) {|news, sub| news << sub.news_piece } end end

I tez tak mam.