ActiveRecord Join Query and select in Rails

前端 未结 5 1780
甜味超标
甜味超标 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:05

    Try This:

    sql = Project.joins(:client).select(:id, :name, :"clients.name AS client_name").to_sql
    data = ActiveRecord::Base.connection.exec_query(sql)
    

    OUTPUT

    [
      {"id"=>1, "name"=>"ProjectName1", "client_name"=>"ClientName1"},
      {"id"=>2, "name"=>"ProjectName2", "client_name"=>"ClientName2"}
    ]
    

提交回复
热议问题