简体   繁体   English

Rails-find_by_sql +存储过程

[英]Rails - find_by_sql + Stored Procedure

I am trying to get objects from my MySQL database using a stored procedure I have created. 我正在尝试使用创建的存储过程从MySQL数据库中获取对象。

@locs = Location.find_by_sql("CALL geodist(100.4058, 37.7907, 10000, 'Sample')")

This results in the following error 这导致以下错误

Location Load (6.4ms)  CALL geodist(100.4058, 37.7907, 10000, 'Sample')
Completed   in 37ms

Mysql2::Error (Commands out of sync; you can't run this command now):

The following however works fine: 但是以下内容可以正常工作:

@locations = Location.connection.select_all("CALL geodist(100.4058, 37.7907, 10000, 'Sample')")

However, it doesn't return objects, only a hash of values. 但是,它不返回对象,仅返回值的哈希。

Is there any way to get find_by_sql to work? 有什么办法可以使find_by_sql工作? If not, how can I manually instantiate AR models without querying the database again? 如果没有,如何手动实例化AR模型,而无需再次查询数据库?

Thanks! 谢谢!

you can build objects yourself by sending every hash to constructor of your active record model 您可以通过将每个哈希发送到活动记录模型的构造函数来自己构建对象

@locations = Location.connection.select_all("CALL geodist(100.4058, 37.7907, 10000, 'Sample')")
results = Array.new
@locations.each do |location|
  results[] = Location.new(location)
end

UPD: by the way it's strange behaviour I just looked at find_by_sql method realization it looks familiar http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-find_by_sql UPD:顺便说一句,这是一种奇怪的行为,我只是看过find_by_sql方法实现,它看起来很熟悉http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-find_by_sql

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

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