【问题标题】:Find records in deeply nested associations with rails在与 rails 的深度嵌套关联中查找记录
【发布时间】:2016-03-31 21:16:55
【问题描述】:

我有以下型号:

class Book < ApplicationRecord
  has_many :chapters
end

class Chapter < ApplicationRecord
  belongs_to :book
  has_many :pages
end

class Page < ApplicationRecord
  belongs_to :chapter
  has_many :paragraphs
end

class Paragrpah < ApplicationRecord
  belongs_to :page
end

现在我想获取特定书中所有段落的列表。比如:

@parapgraphs = Paragraph.pages.chapters.book.where(:title => 'My Book')

当我这样做时,我得到:

undefined method 'chapters' for 'pages'

我正在使用 Rails 4.2 和 Ruby 2.2

【问题讨论】:

  • 章节方法应该是“章节”,如:@parapgraphs = Paragraphs.pages.chapter.book.where(:title => 'My Book')
  • 这应该可以解决问题Paragraphs.includes(page: { chapter: :book }).where(books: { title: 'MyBook' })(类似于stackoverflow.com/questions/18082096/…

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord where-clause


【解决方案1】:

如果您希望任何这些对象之间的链接始终存在且可查询,请考虑添加 has_many through 关系。

http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

如果它更像是一次查询,你可以做这样的事情

@paragraphs = Paragraph.joins(page: { chapter: :book }).where(books: { title: 'My Book' })

【讨论】:

  • where 子句使用表名,而不是关系名(应为where(books: { title: 'some title' })
【解决方案2】:

试试这个

@paragraphs = Book.find_by(title: 'My book').chapters.map{ |c| c.pages.map{ |p| p.paragraphs.to_a }.flatten }.flatten

【讨论】:

  • 这可能需要很长时间来计算。您应该尽可能使用 SQL,而不是使用 Ruby。特别是在这种情况下
  • 没错,这更像是一个快速的'n'dirty
猜你喜欢
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-16
  • 2011-07-16
相关资源
最近更新 更多