11
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ActiveRecord の take と first の違いは?

Posted at

どちらも LIMIT 1 した結果を返す。
ただし first は、order の指定がなければプライマリーキーでソートする。
となっているようです。

require "active_record"
ActiveRecord::Base.logger = ActiveSupport::Logger.new(STDOUT)
ActiveSupport::LogSubscriber.colorize_logging = false
ActiveRecord::Migration.verbose = false
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
silence_stream(STDOUT) do
  ActiveRecord::Schema.define do
    create_table :users do |t|
      t.string :name
    end
  end
  class User < ActiveRecord::Base
  end
  User.create!
end

User.take
User.first
User.order(:name).first
# >>   User Load (0.1ms)  SELECT  "users".* FROM "users" LIMIT 1
# >>   User Load (0.1ms)  SELECT  "users".* FROM "users"  ORDER BY "users"."id" ASC LIMIT 1
# >>   User Load (0.1ms)  SELECT  "users".* FROM "users"  ORDER BY "users"."name" ASC LIMIT 1
11
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?