diff options
Diffstat (limited to 'activerecord')
-rw-r--r-- | activerecord/lib/active_record/enum.rb | 10 | ||||
-rw-r--r-- | activerecord/test/cases/enum_test.rb | 13 | ||||
-rw-r--r-- | activerecord/test/schema/schema.rb | 4 |
3 files changed, 15 insertions, 12 deletions
diff --git a/activerecord/lib/active_record/enum.rb b/activerecord/lib/active_record/enum.rb index c042a2f232..3dd093b8a2 100644 --- a/activerecord/lib/active_record/enum.rb +++ b/activerecord/lib/active_record/enum.rb @@ -72,10 +72,16 @@ module ActiveRecord _enum_methods_module.module_eval do # def status=(value) self[:status] = STATUS[value] end define_method("#{name}=") { |value| - unless enum_values.has_key?(value) || enum_values.has_value?(value) || value.blank? + if enum_values.has_key?(value)|| value.blank? + self[name] = enum_values[value] + elsif enum_values.has_value?(value) + # Assigning a value directly is not a end-user fetaure, hence it's not documented. + # This is used internally to make building objects from the generated scopes work + # as expected, i.e. +Conversation.archived.build.archived?+ should be true. + self[name] = value + else raise ArgumentError, "'#{value}' is not a valid #{name}" end - self[name] = enum_values[value] } # def status() STATUS.key self[:status] end diff --git a/activerecord/test/cases/enum_test.rb b/activerecord/test/cases/enum_test.rb index 47e3dfc3ad..c09e58fbf1 100644 --- a/activerecord/test/cases/enum_test.rb +++ b/activerecord/test/cases/enum_test.rb @@ -79,12 +79,13 @@ class EnumTest < ActiveRecord::TestCase assert_equal 2, Book::STATUS[:published] end - test "first_or_initialize with enums' scopes" do - class Issue < ActiveRecord::Base - enum status: [:open, :closed] - end + test "building new objects with enum scopes" do + assert Book.written.build.written? + assert Book.read.build.read? + end - assert Issue.open.empty? - assert Issue.open.first_or_initialize + test "creating new objects with enum scopes" do + assert Book.written.create.written? + assert Book.read.create.read? end end diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 9f504801af..ac546fc296 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -327,10 +327,6 @@ ActiveRecord::Schema.define do t.string :color end - create_table :issues, force: true do |t| - t.integer :status - end - create_table :items, force: true do |t| t.column :name, :string end |