diff options
author | Godfrey Chan <godfreykfc@gmail.com> | 2014-01-03 09:31:01 -0800 |
---|---|---|
committer | Godfrey Chan <godfreykfc@gmail.com> | 2014-01-03 09:31:01 -0800 |
commit | 788bb40e3887e2718f07be769b80818d653638f0 (patch) | |
tree | f66c4334fc261ed18955853ce3da796935a24a4f /activerecord/lib/active_record | |
parent | 97e7ca48c139ea5cce2fa9b4be631946252a1ebd (diff) | |
download | rails-788bb40e3887e2718f07be769b80818d653638f0.tar.gz rails-788bb40e3887e2718f07be769b80818d653638f0.tar.bz2 rails-788bb40e3887e2718f07be769b80818d653638f0.zip |
Building new records with enum scopes now works as expected
Previously, this would give an `ArgumentError`:
class Issue < ActiveRecord::Base
enum :status, [:open, :finished]
end
Issue.open.build # => ArgumentError: '0' is not a valid status
Issue.open.create # => ArgumentError: '0' is not a valid status
PR #13542 muted the error, but the issue remains. This commit fixes
the issue by allowing the enum value to be written directly via the
setter:
Issue.new.status = 0 # This now sets status to :open
Assigning a value directly via the setter like this is not part of the
documented public API, so users should not rely on this behavior.
Closes #13530.
Diffstat (limited to 'activerecord/lib/active_record')
-rw-r--r-- | activerecord/lib/active_record/enum.rb | 10 |
1 files changed, 8 insertions, 2 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 |