未验证 提交 55a7051a 编写于 作者: D David Heinemeier Hansson 提交者: GitHub

Add negative scopes for all enum values (#35381)

Add negative scopes for all enum values
上级 3ee0dabb
* Add negative scopes for all enum values.
Example:
class Post < ActiveRecord::Base
enum status: %i[ drafted active trashed ]
end
Post.not_drafted # => where.not(status: :drafted)
Post.not_active # => where.not(status: :active)
Post.not_trashed # => where.not(status: :trashed)
*DHH*
* Fix different `count` calculation when using `size` with manual `select` with DISTINCT.
Fixes #35214.
......
......@@ -31,7 +31,9 @@ module ActiveRecord
# as well. With the above example:
#
# Conversation.active
# Conversation.not_active
# Conversation.archived
# Conversation.not_archived
#
# Of course, you can also query them directly if the scopes don't fit your
# needs:
......@@ -196,9 +198,13 @@ def enum(definitions)
define_method("#{value_method_name}!") { update!(attr => value) }
# scope :active, -> { where(status: 0) }
# scope :not_active, -> { where.not(status: 0) }
if enum_scopes != false
klass.send(:detect_enum_conflict!, name, value_method_name, true)
klass.scope value_method_name, -> { where(attr => value) }
klass.send(:detect_enum_conflict!, name, "not_#{value_method_name}", true)
klass.scope "not_#{value_method_name}", -> { where.not(attr => value) }
end
end
end
......
......@@ -43,6 +43,11 @@ class EnumTest < ActiveRecord::TestCase
assert_equal books(:ddd), Book.forgotten.first
assert_equal books(:rfr), authors(:david).unpublished_books.first
end
test "find via negative scope" do
assert Book.not_published.exclude?(@book)
assert Book.not_proposed.include?(@book)
end
test "find via where with values" do
published, written = Book.statuses[:published], Book.statuses[:written]
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册