0

I am trying to filter my posts and I grab them using this query.

@posts = Post.all.includes(:course).where("courses.name IN (#{@user.courses.map(&:name).collect { |s| "'#{s}'"  }.join(',') })").references(:course).order("posts.created_at DESC")

I am not familiar with postgresql and know there are some differences. How do I change this to query in postgres?

1
  • 1
    Have you tried running that query? It might just work. Commented Jul 28, 2016 at 3:12

1 Answer 1

1

Your query will work as it is. But you can modify the query to avoid the unnecessary operations you are doing:

@posts = 
  Post.all.includes(:course).where("courses.name IN (?)", @user.courses.map(&:name)).order("posts.created_at DESC")

Rails will take care of joining the values in this array @user.courses.map(&:name)

You don't need to do it manually.

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

1 Comment

You are right, it works, I was switching to postgres as I posted this question, but Im glad you show me this simplified query, thank you!

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.