内连接选择多列

时间:2015-01-21 20:58:09

标签: ruby-on-rails rails-activerecord

如果我提交

Role.select("roles.character, actors.lname AS actors_lname").joins(:actor)

它返回:

Role Load (0.0ms) SELECT roles.character, actors.lname AS actors_lname 
FROM "roles" INNER JOIN "actors" ON "actors"."id" = "roles"."actor_id"
#<ActiveRecord::Relation [#<Role id: nil, character: "Ellis Boyd 'Red' Redding">, 
#<Role id: nil, character: "Andy Dufresne">, #<Role id: nil, character: "Warden Norton">]>

为什么不显示actors.lname列?

1 个答案:

答案 0 :(得分:2)

使用select

Order.select("orders.id, customers.name").joins(:customers)

如果您使用别名

,则可以获取相关值
orders = Order.select("orders.id, customers.name AS customer_name").joins(:customers)

# you must call the method implicitly, or use .attributes
orders.first.customer_name

请注意,customer_name的值不会出现在记录检查中。因此以下代码

orders.first
IRB中的

不会打印出属性。