Ruby on Rails的:是否有以从数据库中检索数据的阵列,而不需要Rails的实例什么方法? [英] Ruby on Rails: Is there a method to retrieve an array of data from the database without Rails needing to instantiate anything?

查看:87
本文介绍了Ruby on Rails的:是否有以从数据库中检索数据的阵列,而不需要Rails的实例什么方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,我尝试从数据数组,而我不需要对数据进行实例化到Ruby对象。其实,这只是引入了一个额外的步骤到我的code单步执行对象,并生成一个新的数组,正是我所需要的数据。

I have a model that I'm trying to retrieve an array of data from, and I don't need the data to be instantiated into Ruby objects. In fact, that just introduces an extra step into my code to step through the objects and generate a new array with just the data I need.

例如:

class Book
  #has attribute in database title
end

我想生成包含所有图书数据库的所有标题的数组。什么是做到这一点的最好方法是什么?

I would like to generate an array which contains all the titles of all the Books in the database. What's the best way to do it?

推荐答案

ActiveRecord的给你一个直接的挂钩,以目前的环境数据库,让您执行SQL语句并返回结果的基本结构(数组或哈希)。参见:<一href="http://ar.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html">http://ar.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html

ActiveRecord gives you a direct hook to the current environment database, allowing you execute SQL statements and returning the result in basic structures (arrays or hashes). See: http://ar.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html

例如:

ActiveRecord::Base.connection.select_values("SELECT title FROM books")

将返回书名(字符串)数组。这不会实例化任何ActiveRecord的实例,并且将更多的内存高效的为您的应用程序。

Will return an array of book titles (strings). This will not instantiate any ActiveRecord instances and will be more memory efficient for your application.

这篇关于Ruby on Rails的:是否有以从数据库中检索数据的阵列,而不需要Rails的实例什么方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆