ruby-on-rails – 如何通过多个模型设置关联
发布时间:2020-12-17 03:49:12 所属栏目:百科 来源:网络整理
导读:我在Rails中有以下三个模型: class Book ActiveRecord::Base has_many :chapters has_many :pagesendclass Chapter ActiveRecord::Base belongs_to :book has_many :pagesendclass Page ActiveRecord::Base belongs_to :chapterend 如何查询如下:Book.firs
我在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来获取整本书的页数.到现在为止,我甚至不知道我是否以正确的方式设置我的模型.如果你能在这里帮助我会很棒. 提前致谢! 解决方法
您可以使用如
here所述的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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |