简体   繁体   中英

Ruby on Rails Select As doesn't work

I am trying to get a "Select As" query statement to work, but keep getting an error and am not sure why it is not working. Per the API docs, the format is correct.

User.select("firstname as fname")

Results in:

  User Load (1.7ms)  SELECT firstname as fname FROM "users"
 => #<ActiveRecord::Relation [#<User id: nil>, #<User id: nil>]

However if i use:

User.select(:firstname)

I get:

  User Load (2.8ms)  SELECT "users"."firstname" FROM "users"
 => #<ActiveRecord::Relation [#<User id: nil, firstname: "John">, #<User id: nil, firstname: "Brian">,

So I can see from the query why it's not returning the results, but I don't understand why its creating the incorrect query. (The actual query I need to use the select as on is more complicated then this query, but I was trying to use the simpler query to try to figure out why it wasn't working properly.

The reason I need to use a select as query is because I have two separate objects from two very different tables that i need to join together and change one of the column names so I can sort by that column. I'm not sure if there is an easier way to change the name prior to combining the objects.

Thanks!

您可以在模型中使用alias_attribute :firstname, :fname ,然后在控制器中使用User.select(:fname)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM