Skip to content

Commit

Permalink
Add the ability to nullify the enum column
Browse files Browse the repository at this point in the history
  • Loading branch information
amrnt committed Dec 31, 2013
1 parent ec46699 commit e0ad9ae
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
22 changes: 22 additions & 0 deletions activerecord/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,25 @@
* Add the ability to nullify the `enum` column.

Example:

class Conversation < ActiveRecord::Base
enum gender: [:female, :male]
end

Conversation::GENDER # => { female: 0, male: 1 }

# conversation.update! gender: 0
conversation.female!
conversation.female? # => true
conversation.gender # => "female"

# conversation.update! gender: nil
conversation.gender = nil
conversation.gender.nil? # => true
conversation.gender # => nil

*Amr Tamimi*

* Connection specification now accepts a "url" key. The value of this
key is expected to contain a database URL. The database URL will be
expanded into a hash and merged.
Expand Down
7 changes: 6 additions & 1 deletion activerecord/lib/active_record/enum.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ module ActiveRecord
# # conversation.update! status: 1
# conversation.status = "archived"
#
# # conversation.update! status: nil
# conversation.status = nil
# conversation.status.nil? # => true
# conversation.status # => nil
#
# You can set the default value from the database declaration, like:
#
# create_table :conversations do |t|
Expand Down Expand Up @@ -62,7 +67,7 @@ def enum(definitions)
_enum_methods_module.module_eval do
# def status=(value) self[:status] = STATUS[value] end
define_method("#{name}=") { |value|
unless enum_values.has_key?(value)
unless enum_values.has_key?(value) || value.blank?
raise ArgumentError, "'#{value}' is not a valid #{name}"
end
self[name] = enum_values[value]
Expand Down
15 changes: 15 additions & 0 deletions activerecord/test/cases/enum_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,21 @@ class EnumTest < ActiveRecord::TestCase
assert_equal "'unknown' is not a valid status", e.message
end

test "assign nil value" do
@book.status = nil
assert @book.status.nil?
end

test "assign empty string value" do
@book.status = ''
assert @book.status.nil?
end

test "assign long empty string value" do
@book.status = ' '
assert @book.status.nil?
end

test "constant to access the mapping" do
assert_equal 0, Book::STATUS[:proposed]
assert_equal 1, Book::STATUS["written"]
Expand Down

0 comments on commit e0ad9ae

Please sign in to comment.