Ryan
Ryan

Reputation: 15

How would I translate this sqlite query into a postgresql query in Ruby on Rails?

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?

Upvotes: 0

Views: 70

Answers (1)

Deepak Mahakale
Deepak Mahakale

Reputation: 23661

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.

Upvotes: 1

Related Questions