Rails中的原始SQL问题

时间:2015-11-24 19:47:19

标签: sql ruby-on-rails ruby activerecord

我使用原始SQL在我的项目中构建SQL编辑器。但是当我调用简单的选择查询时,我得到了这个结果:

[{"id"=>1, "name"=>"Ukraine", "phone_code"=>"+38", "created_at"=>"2015-11-23 21:52:49.415748", "updated_at"=>"2015-11-23 21:52:49.415748", 0=>1, 1=>"Ukraine", 2=>"+38", 3=>"2015-11-23 21:52:49.415748", 4=>"2015-11-23 21:52:49.415748"}]

查询很简单:

SELECT * FROM countries

如您所见,相同的字段首先显示属性标题,然后第二次显示整数索引。

我使用此代码两个仅输出带属性标题的元素:

@headers = @result.first.keys
@count = @headers.size / 2

之后我迭代了标题:

<tr>
    <% (0...@count).each do |i| %>
        <th><%= @headers[i] %></th>
    <% end %>
</tr>

但我认为这不是最好的解决方案。那么,只输出具有适当标题的元素的最佳方法是什么,而不是使用索引?

3 个答案:

答案 0 :(得分:0)

尝试select_all

$ bin/rails c

Loading development environment (Rails 4.2.4)
>> result = ActiveRecord::Base.connection.select_all "SELECT * FROM wingnuts"
   (0.4ms)  SELECT * FROM wingnuts
=> #<ActiveRecord::Result:0x007fb92fbcdb18 @columns=["id", "size"], @rows=[[1, 10], [2, 11], [3, 12]], @hash_rows=nil, @column_types={}>
>> result.each { |row| puts row.inspect }
{"id"=>1, "size"=>10}
{"id"=>2, "size"=>11}
{"id"=>3, "size"=>12}
=> [{"id"=>1, "size"=>10}, {"id"=>2, "size"=>11}, {"id"=>3, "size"=>12}]

答案 1 :(得分:0)

如果您已经拥有要从哈希中提取的已知密钥,那么您可以使用Hash#select方法,如下所示:

a = [{"id"=>1, "name"=>"Ukraine", "phone_code"=>"+38", "created_at"=>"2015-11-23 21:52:49.415748", "updated_at"=>"2015-11-23 21:52:49.415748", 0=>1, 1=>"Ukraine", 2=>"+38", 3=>"2015-11-23 21:52:49.415748", 4=>"2015-11-23 21:52:49.415748"}]
known_keys = %w(id name phone_code created_at updated_at)
a[0].select { |key, value| known_keys.include? key }
# => {"id"=>1, "name"=>"Ukraine", "phone_code"=>"+38", "created_at"=>"2015-11-23 21:52:49.415748", "updated_at"=>"2015-11-23 21:52:49.415748"}

答案 2 :(得分:0)

我不确定你为什么要以这种方式回来,但回答你的问题&#34;只输出具有适当标题的元素而不是索引的最佳方法是什么?&#34;:

# The new, properly formatted object
hash_of_proper_keys = Hash.new

# Assuming country is in the form of a hash of values
country.each do |key, value|
    hash_of_proper_keys[key] = value unless key.is_a? integer
end