2017-06-01 102 views
0

我有3个型号:作家,书,页。导轨访问所有has_many通过记录

Writer has_many :books 
Writer has_many :pages, through: :books 
Book has_many :pages 

我想显示所有属于通过这本书作家的页面,但它给出了一个错误:

Writer.first.books #=> works, shows all writer books 
Book.first.pages #=> works, shows all book pages 
Writer.first.books.pages #=> does not work, must in theory display all pages that belong to the writer 

什么是显示所有网页的最佳方式,使用each do |x|除外?

回答

0

Writer.first.books是一个集合,将显示第一个Writer中的所有书籍,这就是为什么在调用pages时看到错误的原因;需要从BookWriter对象(不是集合)调用pages

因此,假设您的关联是完全一样,例如:

class Writer < ApplicationRecord 
    has_many :books 
    has_many :pages, through: :books 
end 

class Book < ApplicationRecord 
    belongs_to :writer 
    has_many :pages 
end 

class Page < ApplicationRecord 
    belongs_to :book 
end 

,你应该能够得到直接调用pagesWriter,像这样:

Writer.first.pages