user12763413
user12763413

Reputation: 1347

Select data in the order of the column name in rails

I am using the below code to fetch data. I want the order of the selected data in the order of id -> last_name -> first_name but the data return is in the order of id -> first_name -> last_name. Please help me find where I am going wrong. I am using rails 5

x=["id", "last_name", "first_name"]
@posts = Post.select(x.map(&:inspect).join(', '))

[#<Post:0x00007f82bba3
  id: 215,
  first_name: "Jack",
  last_name: "Wills">,
 #<Post:0x00007f82bba3
  id: 216,
  first_name: "Ross",
  last_name: "Denny">]

Upvotes: 1

Views: 61

Answers (1)

user12763413
user12763413

Reputation: 1347

x=["id", "last_name", "first_name"]
@posts = Post.select(x.map(&:inspect).join(', '))
@posts = @posts.map{ |l| l.attributes.slice(*x)}

This is how I solved it.

Upvotes: 1

Related Questions