ActiveRecord Join Query and select in Rails

前端 未结 5 1769
甜味超标
甜味超标 2021-01-30 10:34

In my rails 4 application, a client (clients table) can have many projects (projects table). I have a column called name in each table. I am trying to write a

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-30 11:18

    You can use :'clients.name' as one of your symbols. For instance:

    Project.select(:id, :name, :'clients.name').joins(:client)
    

    I like it better because it seems like Rails understands it, since it quotes all parameters:

    SELECT "projects"."id", "projects"."name", "clients"."name"
    FROM "projects"
    INNER JOIN "clients" ON "clients"."id" = "projects"."client_id"
    

    (I'm not 100% sure that's the exact SQL query, but I'm fairly certain and I promise it will use "clients"."name")

提交回复
热议问题