Getting typed results from ActiveRecord raw SQL

后端 未结 6 2031
Happy的楠姐
Happy的楠姐 2020-12-29 20:51

In Sequel, I can do:

irb(main):003:0> DB[\"select false\"].get
=> false

Which returns a false boolean. I\'d like to be able to do so

6条回答
  •  太阳男子
    2020-12-29 21:30

    In Rails 6, Person.connection.select_all(sql_query).to_a

    ...will return an array of hashes whose values are type-casted. Example:

    [{"id"=>12, "name"=>"John Doe", "vip_client"=>false, "foo"=> nil, "created_at"=>2018-01-24 23:55:58 UTC}]
    

    If you prefer an OpenStruct, use Mike's suggestion:

    Person.connection.select_all(sql_query).to_a.map {|r| OpenStruct.new(r) }

    If you prefer symbols as keys, call map(&:symbolize_keys) after to_a.

提交回复
热议问题