I currently have a .find method in one of my rails controller actions – the relevant part is:
.find(:all, :select => 'last_name as id, last_name as name')
I am getting some odd behaviour trying to alias the last_name column as id – if I alias it as anything else, it works fine (i can do last_name as xyz and it outputs the last name in a column called xyz, but as I am using this to populate a drop-down where I need to have the name in the id column, i need it to be called ‘id’).
I should point out that it does output an id column, but it is always "id":0.
Could anyone shed any light on what I need to do to get this column aliased as ‘id’?
Thanks!
I’m not sure of how you can do this in a Rails query statement. Rails is going to try and take over the
idcolumn, casting the value returned by the database asidwith the type of column thatidis (presumably integer). That’s why youridcolumn keeps getting set to 0, because"string".to_i #=> 0However, there is a way to do it, once you have the results back.
Since you have the question tagged as Rails 3, it is preferable to use the new ActiveRelation syntax. You can do the following:
That will get you a hash with the
idvalue as the text string valuelast_nameand anamevalue as the same.Hope that helps!