Efficient ActiveRecord has_and_belongs_to_many query

梦想的初衷 提交于 2019-12-05 03:06:40

With a has_many :through relationship, you could use this:

pages = Page.joins(:pages_paragraphs).where(:pages_paragraphs => {:paragraph_id => 1})

Take a look at Specifying Conditions on the Joined Tables here: http://guides.rubyonrails.org/active_record_querying.html

If you want the pages and paragraphs together:

pages = Page.joins(:pages_paragraphs => :paragraph).includes(:pages_paragraphs => :paragraph).where(:pages_paragraphs => {:paragraph_id => 1})

With a has_and_belongs_to_many:

pages = Page.joins("join pages_paragraphs on pages.id = pages_paragraphs.page_id").where(["pages_paragraphs.paragraph_id = ?", paragraph_id])

You can use includes for this :

pages = Paragraph.includes(:pages).find(paragraph_id).pages

You can use eager_load for this

pages = Paragraph.eager_load(:pages).find(paragraph_id).pages

I found an article all about this sort of thing: 3 ways to do eager loading (preloading) in Rails 3 & 4 by Robert Pankowecki

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!