方法区分ActiveRecord :: Base.connection mysql加入查询结果?

时间:2017-12-08 05:48:31

标签: mysql ruby-on-rails ruby activerecord

我的查询:

records = ActiveRecord::Base.connection.execute("SELECT * FROM leads WHERE leads.status=1 AND leads.account_id=1 AND leads.id > 253380")

结果:

    records.first
[253381, 1, "first", "king", "CEO", "Jewelry & Toys", "11111", "22222", nil, nil, nil, nil]

    records.fields
["id", "account_id", "first_name", "last_name", "job_title", "department", "work_number", "mobile_number", "address", "city", "state", "zipcode"]

到目前为止一切都很好,但现在当我离开时加入查询如下:

records = ActiveRecord::Base.connection.execute("SELECT * FROM leads LEFT JOIN lead_details ON lead_details.id=leads.id AND lead_details.account_id = leads.account_id WHERE leads.status=1 AND leads.account_id=1 AND leads.id > 253380")

结果:

    records.first
[253381, 1, "first", "king", "CEO", "Jewelry & Toys", "11111", "22222", nil, nil, nil, nil, nil, nil, nil, nil]

    records.fields
["id", "account_id", "first_name", "last_name", "job_title", "department", "work_number", "mobile_number", "address", "city", "state", "zipcode", "id", "account_id", "stars", "score"]

注意:在最后一个数组中"id", "account_id", "stars", "score"是连接表的列

当我尝试将记录转换为哈希时第二个idaccount_id将覆盖第一个idaccount_id,结果将是这样的

{"id"=>nil,
   "account_id"=>nil,
   "first_name"=>"first",
   "last_name"=>"king",
   "job_title"=>"CEO",
   "department"=>"Jewelry & Toys",
   "work_number"=>"11111",
   "mobile_number"=>"22222",
   "address"=>nil,
   "city"=>nil,
   "state"=>nil,
   "zipcode"=>nil,
   "stars"=>nil,
   "score"=>nil
  }

如何解决这种数据覆盖问题?有没有办法根据表名或其他东西将查询结果分区为嵌套数组?

1 个答案:

答案 0 :(得分:0)

因此,如果我理解正确,第二个表中的列将覆盖第一个表中的列。

我建议不要选择不需要的列。

您可以通过在SQL中明确定义要加载的第二个表中的哪些列来实现:" stars"和"得分"。

"SELECT leads.*, lead_details.stars, lead_details.score FROM leads LEFT JOIN lead_details ON lead_details.id=leads.id AND lead_details.account_id = leads.account_id WHERE leads.status=1 AND leads.account_id=1 AND leads.id > 253380"