0

Right now i am getting the 25 most recent posts

posts = Post.where(public: true).limit(25).order(created_at: :desc)

and when i am rendering it i use an include

render :json => posts.as_json(:include => [:user])

this is to get the user who made the post and send it ie:

{
      "id": 43,
      "title": "asdfasdfs",
      "story": "adfaf sdf sd asdf sdf asdf saf adf",
      "created_at": "2017-05-10T22:40:54.587Z",
      "user": {
        "id": 4,
        "first_name": "heelo",
        "last_name": "heelo",
}

which looks like it works great but when looking in the console. its making 26 queries, one to get the posts,

 SELECT  "posts".* FROM "posts" WHERE (public = true) ORDER BY "posts"."created_at" DESC LIMIT ?  [["LIMIT", 25]]

and 25 more to get the user for each post

 SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", XXX], ["LIMIT", 1]]

to gets its user. Isnt there some way i can do a join to avoid making 25 more queries. i tried

posts = Post.joins(:user).where(public: true).limit(25).order(created_at: :desc)

but it doesnt seem to do anything. Any advice?

1 Answer 1

1

Try using includes to cut it down to only two queries.

posts = Post.includes(:user).where(public: true).limit(25).order(created_at: :desc)

This will query the last 25 posts in one query and all the associated users in another query.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.