我在以下三个模型Rails
:
class Book < ActiveRecord::Base
has_many :chapters
has_many :pages
end
class Chapter < ActiveRecord::Base
belongs_to :book
has_many :pages
end
class Page < ActiveRecord::Base
belongs_to :chapter
end
如何进行查询:Book.first.pages.count
获得整本书的页数。到目前为止,我什至不知道我是否建立了正确的模型。如果您能在这里帮助我,那就太好了。
提前致谢!
您可以使用此处has_many
through
概述的关系
class Book < ActiveRecord::Base
has_many :chapters
has_many :pages, through: :chapters
end
class Chapter < ActiveRecord::Base
belongs_to :book
has_many :pages
end
class Page < ActiveRecord::Base
belongs_to :chapter
end
这使您能够 book.pages.count
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句