Slicedpan
Slicedpan

Reputation: 5015

ActiveRecord attribute names with table name

I am using associations to join a number of models together and select them in a single query, however when two of the models share a column name, only the second one in the select statement is used. Is there any way of using a fully qualified name i.e. prefixed with the table name, so that the attributes hash can contain both column values?

Examples:

Class User < ActiveRecord::Base
  belongs_to :role
end

#This query will only allow me to see the name of the role
User.joins(:role).select('users.name', 'role.name')

#Using the raw connection removes the table name from the resultset also
User.connection.select("users.name, roles.name FROM users JOIN roles ON users.role_id = roles.id")

=> #<ActiveRecord::Result:0x00000000000000 @columns=["name", "name"], @rows=[["some_user", "admin"]]...

Upvotes: 0

Views: 582

Answers (1)

Steve Robinson
Steve Robinson

Reputation: 3939

Try this:

User.joins(:role).select('users.name as user_name, role.name as role_name')

Upvotes: 1

Related Questions