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")

我需要将此结果映射到某个对象,或者像这样。谢谢。

4

1 回答 1

2

我的理解是,您可以在任何模型上执行这样的 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: {}
于 2011-04-02T14:47:07.610 回答