Mysql2 ::对象的结果

时间:2011-04-02 14:10:09

标签: ruby-on-rails 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")

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

1 个答案:

答案 0 :(得分: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: {}