Rails/ActiveRecord Sub collection
I have three models: Store, A开发者_运维问答uthor, 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
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
...
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.
精彩评论