LoginSignup
7
2

More than 5 years have passed since last update.

ActiveRecord 5 系から enum で定義した名前をそのまま where でも使えるようになっていた

Last updated at Posted at 2017-07-15
gem "activerecord", "4.2.8"
require "active_record"

ActiveRecord::Migration.verbose = false
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Schema.define do
  create_table :users do |t|
    t.integer :foo
  end
end

class User < ActiveRecord::Base
  enum foo: [:a, :b]
end

User.foos                  # => {"a"=>0, "b"=>1}
User.defined_enums         # => {"foo"=>{"a"=>0, "b"=>1}}

User.create!(foo: :a)

User.a                     # => #<ActiveRecord::Relation [#<User id: 1, foo: 0>]>
User.where(foo: :a).to_sql # => "SELECT \"users\".* FROM \"users\" WHERE \"users\".\"foo\" = NULL"
User.where(foo: :a)        # => #<ActiveRecord::Relation []>

最後の3行は ActiveRecord 5.1.2 で次のようになります

User.a                     # => #<ActiveRecord::Relation [#<User id: 1, foo: "a">]>
User.where(foo: :a).to_sql # => "SELECT \"users\".* FROM \"users\" WHERE \"users\".\"foo\" = 0"
User.where(foo: :a)        # => #<ActiveRecord::Relation [#<User id: 1, foo: "a">]>

where(foo: :a) と自然に書けるようになっていることがわかります。

自分からは、よっぽどのことがないかぎり enum を使うことはないですが、必要になったときに自然に書けるのはありがたいです。

7
2
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
7
2