简体   繁体   English

在Rails中以字符串形式获取SQL查询的结果

[英]Get results of SQL Query as string in Rails

when i run a complicated sql query from the command line like this 当我从这样的命令行运行复杂的sql查询时

sqlite3 db/development.sqlite3 < queries.sql

i get a result like this 我得到这样的结果

Competency Name|Component Name|3.77|4.0|0.23
Another Competency Name|Another Component Name|3.77|4.0|0.23

which i can easily parse like this 我可以像这样轻松解析

hidden_strengh_strings = results.split("\n")[1..-1];
hidden_strengh_strings.each do |hidden_strength_string|
  hidden_strengh_values = hidden_strength_string.split("|");

  hidden_strength = {}
  hidden_strength.merge!(:competency => hidden_strengh_values[0]);
  hidden_strength.merge!(:component => hidden_strengh_values[1]);
  hidden_strength.merge!(:reviewer_average_score => hidden_strengh_values[2]);
  hidden_strength.merge!(:reviewee_average_score => hidden_strengh_values[3]);
  hidden_strength.merge!(:exceedance => hidden_strengh_values[4]);

  hidden_strengths << hidden_strength
end

but i have no idea how to get these results from within ActiveRecord. 但我不知道如何从ActiveRecord中获得这些结果。

results = ActiveRecord::Base.connection.execute(File.open(Rails.root.join('queries.sql'), 'r') { |f| f.read } );

doesn't seem to do what i want it to. 似乎没有按照我的意愿去做。

i'd be happy to take any approach to solve this problem. 我很乐意采取任何方法来解决这个问题。 even rewriting the sql from within the ActiveRecord DSL. 甚至从ActiveRecord DSL内重写sql。 but i need help finding the right direction. 但是我需要帮助找到正确的方向。

thanks : ) 谢谢 : )

Nishant lead me to the solution. Nishant带领我找到解决方案。

ActiveRecord::Base.connection.execute

Works fine its just that the query started with: 工作良好,只是查询始于:

select 'HIDDEN STRENGTHS';

so exec ended at the semicolon. 因此高管以分号结尾。

Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM