🖥

Rails4 | Model.select (Scroll columns on SQL queries)

2019/04/16に公開

.select

For example, if you write Only id columns can be obtained as internally issued SQL.

 User.select(:id) 

Let's check it in practice. ( users the part of users . id )

 User.select(:id).to_sql # => "SELECT `users`.`id` FROM `users`" 

Of course, in this case, "unspecified columns" can not be obtained on the object. Even if you get only id, you can't use name to send it out. k.

 User.select(:id).first.name # => NoMethodError: undefined method `name' 

Use

There is a huge amount of data in one column. Use it when eating memory.

(There is also a story that you can get only the columns you need at any time.)

Rails 3 or earlier

The way to write is old in Rails3. The following syntax is obsolete in Rails 4.

 User.all(:select => 'id') 

reference

environment

  • Rails 4.2.6

Original by

Rails4 | Model.select ( SQLクエリ上でカラムを絞る )

About

About this translattion

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2019-04-16

Discussion