开发者

Mysql2::Result to Objects

开发者 https://www.devze.com 2023-02-21 06:55 出处:网络
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, `开发者_如何学Cusers` u WHERE u.id

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, `开发者_如何学Cusers` 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.


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: {}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号