2010-05-25 79 views
0

我有三個模型:商店,作者,書籍Rails/ActiveRecord Sub collection

商店有許多作者有很多書籍。

什麼是最清潔的方式來獲得在商店所有書籍的集合?

這工作:

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

有東西在活動記錄我失蹤,使這一清潔?

傑克

回答

1

這可能工作...

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 

有了這個代碼,您可以使用@store.books ...

0

你想要的是has_many通過。它的工作原理是這樣的:

# 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 

現在你可以說@store.books,它應該只是工作。