Mysql2::结果到对象

发布于 2024-10-30 13:49:22 字数 288 浏览 2 评论 0原文

如何将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

那片花海 2024-11-06 13:49:22

我的理解是,您可以在任何模型上执行类似的 sql 查询,它将返回数据作为该模型的实例。阅读 find_by_sql。这是文档中的示例。请注意,它返回一个 Post 对象:

Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
> [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]

Rails 3 查询语法应该为您提供获取此信息所需的一切。我会尽可能远离原始 SQL,你会发现自己很快就与特定数据库绑定在一起。请查看此处寻找一些灵感。

将参数传递给 find_by_sql 可以这样完成:

irb(main):015:0> y Location.find_by_sql(["select address, name from locations where name = :name and address = :address", {:address => "Arts Court 2 Daly Ave, Ottawa, ON", :name => "Studio B"}])
--- 
- !ruby/object:Location 
  attributes: 
  name: Studio B
  address: Arts Court 2 Daly Ave, Ottawa, ON
  attributes_cache: {}

changed_attributes: {}

destroyed: false
marked_for_destruction: false
new_record: false
previously_changed: {}

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:

Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
> [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]

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:

irb(main):015:0> y Location.find_by_sql(["select address, name from locations where name = :name and address = :address", {:address => "Arts Court 2 Daly Ave, Ottawa, ON", :name => "Studio B"}])
--- 
- !ruby/object:Location 
  attributes: 
  name: Studio B
  address: Arts Court 2 Daly Ave, Ottawa, ON
  attributes_cache: {}

changed_attributes: {}

destroyed: false
marked_for_destruction: false
new_record: false
previously_changed: {}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文