【问题标题】:Mysql2::Result to ObjectsMysql2::Result 到对象
【发布时间】:2011-04-02 14:10:09
【问题描述】:

如何将 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")

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

【问题讨论】:

    标签: ruby-on-rails mysql2


    【解决方案1】:

    我的理解是,您可以在任何模型上执行这样的 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 以获得一些灵感。

    将参数传递给 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: {}
    

    【讨论】:

    • 谢谢,如何将两个或更多参数传递给 find_by_sql 方法?
    • 已解决 Question.find_by_sql([sql, '2011-04-06', 1])
    • 我在答案中添加了一个示例。
    猜你喜欢
    • 1970-01-01
    • 2012-01-18
    • 2021-03-14
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 2011-05-04
    • 2013-04-25
    相关资源
    最近更新 更多