Cui Pengfei 崔鹏飞
Cui Pengfei 崔鹏飞

Reputation: 8305

ActiveRecord: how to select helper method result as a field?

When using active record, I can select fields like this:

Model.select(:a_col,:b_col)

If the model has some helper methods defined, then I am doing this(which feels lame):

Model.all.map{|m|{a:m.a_col,b:m.b_col,c:m.someMethodCall()}}

Is there a way to do it like this?

Model.select(:a_col,:b_col,:someMethodCall)

Upvotes: 0

Views: 248

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176362

No, this is not possible. select translates the symbol into the corresponding SQL database column

Model.select(:foo)

becomes

SELECT foo FROM models

as opposite to

SELECT * FROM models

Your database has no knowledge of the methods defined in your Ruby class. Therefore, what you are trying to achieve is not possible.

Upvotes: 6

Related Questions