0

I am using Rails5.2 and read project code like

blog = Blog.includes(:posts).references(:posts).where(uuid: params[:uuid])

When I searched on the internet, I got examples like link

Blog.includes(:posts).where(name: 'Blog 1').references(:posts)

Are there any differences for placing where clause before or after references clause?

Mike
  • 313
  • 4
  • 15

2 Answers2

1

You should read joins, includes, preload, eager_load & references from reference

Note: includes do not create separate query always.

references is used after includes & before where clause (I used while migrating project from rails-3 to rails-5 to resolve column ambiguity issue)

Read this also.

ray
  • 5,454
  • 1
  • 18
  • 40
0

If you check this link here, you can see the definition of references.

In short terms, the includes will run a separate query to get all your posts (in your example) instead of getting them every time you loop through a blog.

Now for references, of you want to add a where condition on the posts, you'll need to add it. In your case, you don't need to include it.

Small example:

blog = Blog.includes(:posts).where(uuid: params[:uuid]) -> will run a query to get the Blog from blogs and a query to get all the posts related to this blog.

In another case, like this: blog = Blog.includes(:posts).references(:posts).where(posts: { name: 'test' }) you'll have to use the references or your where condition will throw an error

Roc Khalil
  • 1,365
  • 6
  • 22
  • note `includes` do not create separate query always. – ray Dec 27 '18 at 11:24
  • Hell! Help me please..how to get data from 3 connected tables ProjectsSow.includes(:project).references(:project).includes(:member_allocation).references(:member_allocation).where(............) ? – Igor Romanchuk Dec 28 '20 at 17:36