🖥
Rails4 | Model.select (Scroll columns on SQL queries)
.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
チャットメンバー募集
何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。
公開日時
2019-04-16
Discussion