aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/enum.rb
diff options
context:
space:
mode:
Diffstat (limited to 'activerecord/lib/active_record/enum.rb')
-rw-r--r--activerecord/lib/active_record/enum.rb23
1 files changed, 16 insertions, 7 deletions
diff --git a/activerecord/lib/active_record/enum.rb b/activerecord/lib/active_record/enum.rb
index 3086f13f96..ea88983917 100644
--- a/activerecord/lib/active_record/enum.rb
+++ b/activerecord/lib/active_record/enum.rb
@@ -32,6 +32,12 @@ module ActiveRecord
# Conversation.active
# Conversation.archived
#
+ # Of course, you can also query them directly if the scopes doesn't fit your
+ # needs:
+ #
+ # Conversation.where(status: [:active, :archived])
+ # Conversation.where.not(status: :active)
+ #
# You can set the default value from the database declaration, like:
#
# create_table :conversations do |t|
@@ -59,15 +65,17 @@ module ActiveRecord
#
# In rare circumstances you might need to access the mapping directly.
# The mappings are exposed through a class method with the pluralized attribute
- # name:
+ # name, which return the mapping in a +HashWithIndifferentAccess+:
#
- # Conversation.statuses # => { "active" => 0, "archived" => 1 }
+ # Conversation.statuses[:active] # => 0
+ # Conversation.statuses["archived"] # => 1
#
- # Use that class method when you need to know the ordinal value of an enum:
+ # Use that class method when you need to know the ordinal value of an enum.
+ # For example, you can use that when manually building SQL strings:
#
# Conversation.where("status <> ?", Conversation.statuses[:archived])
#
- # Where conditions on an enum attribute must use the ordinal value of an enum.
+
module Enum
def self.extended(base) # :nodoc:
base.class_attribute(:defined_enums)
@@ -85,7 +93,7 @@ module ActiveRecord
@mapping = mapping
end
- def type_cast_from_user(value)
+ def cast(value)
return if value.blank?
if mapping.has_key?(value)
@@ -97,11 +105,12 @@ module ActiveRecord
end
end
- def type_cast_from_database(value)
+ def deserialize(value)
+ return if value.nil?
mapping.key(value.to_i)
end
- def type_cast_for_database(value)
+ def serialize(value)
mapping.fetch(value, value)
end