Ganesh Sagare
Ganesh Sagare

Reputation: 375

How to pluck multiple attributes with nil values in Rails?

I have a User model. User model has a name, phone_no, acc_no, ... fields. I wanted to pluck 3 fields i.e name, phone_no and acc_no. For that I am using

User.pluck(:name, :phone_no, :acc_no)

There is no presence validation on phone_no and acc_no, thats why it gives me following result

[
 ['xyz', '1234'],
 ['pqr', '4567', '12345678'],
 ['abc']
]

I need result like

 [
  ['xyz', '1234', nil],
  ['pqr', '4567', '12345678'],
  ['abc', nil, nil]
 ]

Is there any way to do this?

Upvotes: 0

Views: 845

Answers (1)

Michael Malov
Michael Malov

Reputation: 1887

Try this

User.only(:name, :phone_no, :acc_no).map { |u| [u.name, u.phone_no, u.acc_no] }

Upvotes: 2

Related Questions