ActiveRecord Join Query and select in Rails

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

    If the column in select is not one of the attributes of the model on which the select is called on then those columns are not displayed. All of these attributes are still contained in the objects within AR::Relation and are accessible as any other public instance attributes.

    You could verify this by calling first.client_name:

    Project.joins(:client)
           .select('projects.id,projects.name,clients.name as client_name')
           .first.client_name
    
    0 讨论(0)
  • 2021-01-30 11:04

    your query don't looses any thing. Actually you have applied join on models and you have written Project.joins(:client) that why it is looking like. means It will hold Project related data as it is and associated data hold with alias name that you have given 'client_name' in your query.

    if you use

    Project.joins(:client)
       .select('projects.id project_id, projects.name projects_name,clients.name as client_name')
    

    then it look like [#, #]

    but it hold all the attribute that you selected.

    0 讨论(0)
  • 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"}
    ]
    
    0 讨论(0)
  • 2021-01-30 11:09

    To get both project table name and client name you can do like below query

    Project.joins(:client).pluck(:name,:'clients.name')

    0 讨论(0)
  • 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")

    0 讨论(0)
提交回复
热议问题