2010-05-25 6 views
0

J'ai trois modèles: Magasin, Auteur, LivresRails/ActiveRecord Sub collection

Magasin a beaucoup d'auteurs qui a beaucoup de livres.

Quelle est la manière la plus propre d'obtenir une collection de tous les livres au magasin?

Cela fonctionne:

@store.authors.collect{|a| a.books}.flatten 

Y at-il quelque chose dans Active Record que je manque ce qui fait plus propre?

Jake

Répondre

1

Cela peut fonctionner ...

class Store < ActiveRecord::Base 
    has_many :authors 
    # I used :uniq because a book can have more than one author, and without 
    # the :uniq you'd have duplicated books when using @store.books 
    has_many :books, :through => :authors, :uniq => true 
end 

class Author < ActiveRecord::Base 
    has_many :books 
end 

class Book < ActiveRecord::Base 
    belongs_to :author 
end 

Avec ce code, vous pouvez utiliser @store.books ...

0

Ce que vous voulez, c'est has_many through. Il fonctionne comme ceci:

# in store.rb 
has_many :authors 
has_many :books, :through => :authors 

# in author.rb 
belongs_to :store 
has_many :books 

# in book.rb 
belongs_to :author 

Maintenant, vous pouvez dire @store.books et il devrait fonctionner.