繁体   English   中英

有没有更好的方法从底部到顶部关系在ActiveRecord中联接这些表?

[英]Is there a better way to join these tables in ActiveRecord from bottom to top relation?

作者has_many书籍

书籍has_many内容

如果我想在所有书籍和所有作者中找到一些重复的部分,例如:“ interest”。 我也希望看到他们的book.title和author.name。

content_section = Content.where(:section  => "interest").select("book_id, section ";

books = Books.where(:id => content_section.map(&:book_id)).select("author_id, title")

authors = Author.where(:id => books.map(&:author_id)).select("name")
  • 问题1:是否有更好的方法来实现这一目标? (在性能问题或其他方面)

  • 问题2:有没有办法使content_section,书籍和作者合并到表中? (在ruby端或MySQL端。)

  • 问题3:content_section.map(&:book_id)是什么意思? 我想知道&:book_id的方法

例如,此SQL(MySQL)将创建一个大表,因此我不需要将所有结果合并到ruby中。 对我来说,在视图模板中进行迭代更容易。 但是自从加入三个表以来,它的性能非常低。

select * from authors, books, contents 

where authors.id = books.author_id and books.id = content.book_id and content.section = "interest"

任何评论表示赞赏。 谢谢。

**更新**

引用后: 在此处输入链接描述,在此处 输入链接描述

我尝试添加模型:

类作者

has_many:content,:through => book

结束

然后我在控制台中尝试了这个:

author.joins(:content).where(:section =>“ interest”)。select(“名称,标题,部分:);

我得到一个SQL:

从作者的内部连接书中选择名称,标题,部分。

  • 这个可以吗 ? 谢谢。

这可以做到:

class Author
  has_many :books
  has_many :contents, :through => :books

  scope :by_section, lambda { |section| joins(:contents).where('contents.section' => section) }
end

然后,您可以致电:

authors = Author.by_section("interest")

另外,您还想知道content_sections.map(&:book_id) 这是content_sections.map { |content_section| section.book_id }的简写。 content_sections.map { |content_section| section.book_id } ,它会生成一个书ID数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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