Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails : Get multiple column values for single record

I want to get values of multiple columns (hopefully as an array) of a single record. I have the column names as an array of string.

Something like:

Model.first.select([:id,:name,:col1,:col2]).values
#=> [1,mrudul,col1_val,col2_val]  

# with column_names as array
# Model.first.select(columns_names.map(&:to_sym)).values  

The problem is that I've the column names as an array of string. How can I achieve this?

like image 711
mrudult Avatar asked Oct 11 '25 17:10

mrudult


1 Answers

this works I think

column_names = ['id','name']

Model.where(id: 123).pluck(column_names.join(','))

or using select

Model.select(column_names.join(',')).where(id: 123)

or

Model.select(column_names.join(',')).first