2011-04-02 57 views
0

如何将Mysql2 :: Result结果转换为某个对象? 我使用:Mysql2 ::结果到对象

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

我需要这个结果映射到某个物体,或smthg这样。 谢谢。

回答

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,您可以非常快速地将它绑定到特定的数据库。看看here获得一些灵感。

传递PARAMS到的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: {} 
+0

谢谢,我怎么能传递两个或更多PARAMS到的find_by_sql方法? – 2011-04-02 15:22:19

+0

解决Question.find_by_sql([sql,'2011-04-06',1]) – 2011-04-02 15:52:48

+0

我给我的答案添加了一个例子。 – mikewilliamson 2011-04-02 16:05:25