Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pluck "as alias_name" from rails active record query

I have this query:

Client.select("name as dname")

Which is working fine.

Client.select("name as dname").first.dname
=> "Google"

Now I want to get all dnames as an array but pluck method does not work as dname is not column name.

2.2.5 :040 > Client.select("name as dname").pluck(:dname)
   (0.6ms)  SELECT dname FROM "clients"
ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column "dname" does not exist

How to get array of dnames? Is there any method like pluck which works on column name alias which is defined using as.

I can do this

Client.select("name as dname").map{|d| d.dname}

But looping through every record is not making any sense to me

like image 330
dnsh Avatar asked Oct 03 '16 13:10

dnsh


2 Answers

Well my understanding of pluck was wrong. from apidock I understood that

Use pluck as a shortcut to select one or more attributes without loading a bunch of records just to grab the attributes you want.

So,

Client.select("name as dname").pluck(:dname)

Should be written like this

Client.pluck("name as dname")
like image 183
dnsh Avatar answered Sep 20 '22 05:09

dnsh


Use this code:

Client.select("name as dname").map{|d| d.dname}
like image 20
Uday kumar das Avatar answered Sep 21 '22 05:09

Uday kumar das