Rails复杂查询

时间:2015-03-19 14:21:46

标签: ruby-on-rails activerecord

我有一个非常复杂的查询,它连接4或5个表,为了更容易,我分两步执行:

首先我使用raw sql获取id:

annex_ids = ActiveRecord::Base.connection.select_all(sql_str)

之后我想要实际的对象,还有一些连接:

@annexes = Annex.includes(:contract, { service_address: {street: :city} }, :billing_address, { contract: [:client] }, :packages).find(annex_ids)

但是我收到以下错误消息:

无法找到所有带ID的附件({" id" => 3},{" id" => 4})(找到0结果,但是正在寻找2)

有人可以帮忙吗?谢谢!

1 个答案:

答案 0 :(得分:1)

Couldn't find all Annexes with IDs ({"id"=>3}, {"id"=>4})此错误,因为查询只需要ids

 annex_ids = ActiveRecord::Base.connection.select_all(sql_str) 

返回

{"id"=>3}, {"id"=>4}

因此从中获取ID,并传递给find

annex_ids.collect!{|c| c.values}

然后将annex_ids传递给查询