mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Merge pull request #25998 from kamipo/enum_with_alias_attribute
Fix `enum` with `alias_attribute`
This commit is contained in:
commit
6510f9980d
2 changed files with 22 additions and 5 deletions
|
@ -161,8 +161,9 @@ module ActiveRecord
|
|||
detect_enum_conflict!(name, name)
|
||||
detect_enum_conflict!(name, "#{name}=")
|
||||
|
||||
decorate_attribute_type(name, :enum) do |subtype|
|
||||
EnumType.new(name, enum_values, subtype)
|
||||
attr = attribute_alias?(name) ? attribute_alias(name) : name
|
||||
decorate_attribute_type(attr, :enum) do |subtype|
|
||||
EnumType.new(attr, enum_values, subtype)
|
||||
end
|
||||
|
||||
_enum_methods_module.module_eval do
|
||||
|
@ -184,15 +185,15 @@ module ActiveRecord
|
|||
|
||||
# def active?() status == 0 end
|
||||
klass.send(:detect_enum_conflict!, name, "#{value_method_name}?")
|
||||
define_method("#{value_method_name}?") { self[name] == value.to_s }
|
||||
define_method("#{value_method_name}?") { self[attr] == value.to_s }
|
||||
|
||||
# def active!() update! status: :active end
|
||||
klass.send(:detect_enum_conflict!, name, "#{value_method_name}!")
|
||||
define_method("#{value_method_name}!") { update! name => value }
|
||||
define_method("#{value_method_name}!") { update!(attr => value) }
|
||||
|
||||
# scope :active, -> { where status: 0 }
|
||||
klass.send(:detect_enum_conflict!, name, value_method_name, true)
|
||||
klass.scope value_method_name, -> { where(name => value) }
|
||||
klass.scope value_method_name, -> { where(attr => value) }
|
||||
end
|
||||
end
|
||||
defined_enums[name.to_s] = enum_values
|
||||
|
|
|
@ -393,6 +393,22 @@ class EnumTest < ActiveRecord::TestCase
|
|||
assert book2.single?
|
||||
end
|
||||
|
||||
test "enum with alias_attribute" do
|
||||
klass = Class.new(ActiveRecord::Base) do
|
||||
self.table_name = "books"
|
||||
alias_attribute :aliased_status, :status
|
||||
enum aliased_status: [:proposed, :written, :published]
|
||||
end
|
||||
|
||||
book = klass.proposed.create!
|
||||
assert book.proposed?
|
||||
assert_equal 'proposed', book.aliased_status
|
||||
|
||||
book = klass.find(book.id)
|
||||
assert book.proposed?
|
||||
assert_equal 'proposed', book.aliased_status
|
||||
end
|
||||
|
||||
test "query state by predicate with prefix" do
|
||||
assert @book.author_visibility_visible?
|
||||
assert_not @book.author_visibility_invisible?
|
||||
|
|
Loading…
Reference in a new issue