简体   繁体   中英

rails access all has_many through records

I have 3 models: Writer, Book, Page.

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

I want to display all the pages that belong to the writer through the book , but it gives out an error:

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

What are the best ways to show all the pages, except of using each do |x| ?

Writer.first.books is a collection and will display all the books from the first Writer , that's why you see an error when calling pages on it; pages need to be called from a Book or Writer object (not a collection).

So, assuming that your associations are complete like, for example:

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

you should be able to get call pages directly on Writer , like this:

Writer.first.pages

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM