Mysql2::结果到对象
如何将 Mysql2::Result 结果转换为某个对象? 我使用:
@users = ActiveRecord::Base.connection.execute("SELECT sum(summ) as prize, u.* FROM `tournaments` t, `users` u WHERE u.id = t.user_id GROUP BY t.user_id ORDER BY prize desc LIMIT 10")
我需要将此结果映射到某个对象,或者像这样的东西。 谢谢。
How I can convert Mysql2::Result result to some object?
I use:
@users = ActiveRecord::Base.connection.execute("SELECT sum(summ) as prize, u.* FROM `tournaments` t, `users` u WHERE u.id = t.user_id GROUP BY t.user_id ORDER BY prize desc LIMIT 10")
I need to map this result to some object, or smthg like this.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的理解是,您可以在任何模型上执行类似的 sql 查询,它将返回数据作为该模型的实例。阅读 find_by_sql。这是文档中的示例。请注意,它返回一个 Post 对象:
Rails 3 查询语法应该为您提供获取此信息所需的一切。我会尽可能远离原始 SQL,你会发现自己很快就与特定数据库绑定在一起。请查看此处寻找一些灵感。
将参数传递给 find_by_sql 可以这样完成:
My understanding is that you can execute a sql query like that on any model and it will return the data as instances of that model. Read up on find_by_sql. This is the example from the docs. Notice that is returns a Post object:
Rails 3 query syntax should give you all you need to get this info though. I would stay away from raw SQL as much as possible, you can find yourself tied to a specific database very quickly like that. Take a look here for some inspiration.
Passing params to find_by_sql can be done like this: