Jake
Jake

Reputation: 363

Rails/ActiveRecord Sub collection

I have three models: Store, Author, Books

Store has many Authors which has many Books.

What is the cleanest way to get a collection of all the books at the store?

This works:

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

Is there something in Active Record that I'm missing that makes this cleaner?

Jake

Upvotes: 0

Views: 414

Answers (2)

Ju Nogueira
Ju Nogueira

Reputation: 8461

This may work...

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

With this code you can use @store.books...

Upvotes: 1

John Hyland
John Hyland

Reputation: 6872

What you want is has_many through. It works like this:

# 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

Now you can say @store.books and it should just work.

Upvotes: 0

Related Questions