mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Explicit mapping for enum
This commit is contained in:
parent
09447929a0
commit
7caa09c5e1
4 changed files with 15 additions and 1 deletions
|
@ -3,6 +3,9 @@ module ActiveRecord
|
|||
#
|
||||
# class Conversation < ActiveRecord::Base
|
||||
# enum status: [:active, :archived]
|
||||
#
|
||||
# # same but with explicit mapping
|
||||
# enum status: {active: 0, archived: 1}
|
||||
# end
|
||||
#
|
||||
# Conversation::STATUS # => { active: 0, archived: 1 }
|
||||
|
@ -41,7 +44,8 @@ module ActiveRecord
|
|||
# def direction() DIRECTION.key self[:direction] end
|
||||
class_eval "def #{name}() #{const_name}.key self[:#{name}] end"
|
||||
|
||||
values.each_with_index do |value, i|
|
||||
pairs = values.respond_to?(:each_pair) ? values.each_pair : values.each_with_index
|
||||
pairs.each do |value, i|
|
||||
# DIRECTION[:incoming] = 0
|
||||
const_get(const_name)[value] = i
|
||||
|
||||
|
|
|
@ -12,14 +12,18 @@ class StoreTest < ActiveRecord::TestCase
|
|||
assert @book.proposed?
|
||||
assert_not @book.written?
|
||||
assert_not @book.published?
|
||||
|
||||
assert @book.unread?
|
||||
end
|
||||
|
||||
test "query state with symbol" do
|
||||
assert_equal :proposed, @book.status
|
||||
assert_equal :unread, @book.read_status
|
||||
end
|
||||
|
||||
test "find via scope" do
|
||||
assert_equal @book, Book.proposed.first
|
||||
assert_equal @book, Book.unread.first
|
||||
end
|
||||
|
||||
test "update by declaration" do
|
||||
|
@ -36,5 +40,9 @@ class StoreTest < ActiveRecord::TestCase
|
|||
assert_equal 0, Book::STATUS[:proposed]
|
||||
assert_equal 1, Book::STATUS[:written]
|
||||
assert_equal 2, Book::STATUS[:published]
|
||||
|
||||
assert_equal 0, Book::READ_STATUS[:unread]
|
||||
assert_equal 2, Book::READ_STATUS[:reading]
|
||||
assert_equal 3, Book::READ_STATUS[:read]
|
||||
end
|
||||
end
|
||||
|
|
|
@ -8,4 +8,5 @@ class Book < ActiveRecord::Base
|
|||
has_many :subscribers, through: :subscriptions
|
||||
|
||||
enum status: [:proposed, :written, :published]
|
||||
enum read_status: {unread: 0, reading: 2, read: 3}
|
||||
end
|
||||
|
|
|
@ -95,6 +95,7 @@ ActiveRecord::Schema.define do
|
|||
t.integer :author_id
|
||||
t.column :name, :string
|
||||
t.column :status, :integer, default: 0
|
||||
t.column :read_status, :integer, default: 0
|
||||
end
|
||||
|
||||
create_table :booleans, :force => true do |t|
|
||||
|
|
Loading…
Reference in a new issue