Shruthi R
Shruthi R

Reputation: 1923

Rails 5 - How to use postgresql query?

In rails 5, I am using pg(postgresql) for a back-end database. Now I want to query through rails and get the data. How can I use IN and ORDER(:created_at, :desc) conditions in a query.

In controller,

PAGE_LIMIT = 5
posts = Post.where("user_id IN (?)", [1,2,3]).order(created_at: :desc)
posts = posts.paginate(params[:page], PAGE_LIMIT)

I am writing a custom method like,

def paginate(page, limit = 5)
  page = page ? page.to_i : 1
  limit = limit.to_i
  offset = (page - 1) * limit
  self.offset(offset).limit(limit)
end

I am new to postgresql. Please help me to solve this issue?

Upvotes: 1

Views: 230

Answers (1)

Anand
Anand

Reputation: 6531

suppose you have User model and you want to get user which has id in [1,2,3]

User.where("id IN (?)", [1,2,3]).order(created_at: :desc)

for more dynamic

x = [1,2,3] 
name = "testing123"
User.where("name = ? AND id IN (?)", name, x).order(created_at: :desc)

for more details you can see Active Record Query

to make it working with pagination for array changes to be done here

modified answer

PAGE_LIMIT = 5
posts_arr = Post.where("user_id IN (?)", [1,2,3]).order(created_at: :desc)
posts = Post.where(id: posts_arr.map(&:id)) #here to get active records of posts to make it working for custom pagination
posts = posts.paginate(params[:page], PAGE_LIMIT)

Upvotes: 2

Related Questions