0
我有三个模型:商店,作者,书籍Rails/ActiveRecord Sub collection
商店有许多作者有很多书籍。
什么是最清洁的方式来获得在商店所有书籍的集合?
这工作:
@store.authors.collect{|a| a.books}.flatten
有东西在活动记录我失踪,使这一清洁?
杰克
我有三个模型:商店,作者,书籍Rails/ActiveRecord Sub collection
商店有许多作者有很多书籍。
什么是最清洁的方式来获得在商店所有书籍的集合?
这工作:
@store.authors.collect{|a| a.books}.flatten
有东西在活动记录我失踪,使这一清洁?
杰克
这可能工作...
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
...
你想要的是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
,它应该只是工作。