스토어, 저자, 서적레일/액티브 레코드 서브 콜렉션
스토어에는 많은 책이있는 많은 저자가 있습니다.
상점에서 모든 책을 가장 깨끗하게 수집하는 방법은 무엇입니까?
이 작동 : 내가 부족이이 청소기를 만드는 액티브 레코드에서 뭔가
@store.authors.collect{|a| a.books}.flatten
있습니까?
제이크
스토어, 저자, 서적레일/액티브 레코드 서브 콜렉션
스토어에는 많은 책이있는 많은 저자가 있습니다.
상점에서 모든 책을 가장 깨끗하게 수집하는 방법은 무엇입니까?
이 작동 : 내가 부족이이 청소기를 만드는 액티브 레코드에서 뭔가
@store.authors.collect{|a| a.books}.flatten
있습니까?
제이크
이 작동 할 수 있습니다 ... 당신이 @store.books
을 사용할 수있는이 코드
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
...
원하는 것은 has_many through입니다. 그것은 다음과 같이 작동
# 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
을 말할 수 있으며, 그것은 바로 작동합니다.