Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add negative scopes for all enum values #35381

Merged
merged 3 commits into from Feb 26, 2019
Merged

Add negative scopes for all enum values #35381

merged 3 commits into from Feb 26, 2019

Conversation

@dhh
Copy link
Member

@dhh dhh commented Feb 23, 2019

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)

Particularly convenient when you want to disallow access in a controller, like Post.not_trashed.find(params[:id]).


Example:

class Post < ActiveRecord::Base
Copy link
Contributor

@abhaynikam abhaynikam Feb 24, 2019

@dhh: I think you need to add extra 2 spaces here. The example structure is broken here https://github.com/rails/rails/blob/negative-enum-scope/activerecord/CHANGELOG.md

Copy link
Contributor

@abhaynikam abhaynikam Feb 24, 2019

Also, I don't know if it matters or not, but we should inherit class Post from ApplicationRecord instead here

Copy link
Member Author

@dhh dhh Feb 25, 2019

I'll do the indent, but ApplicationRecord is really a Rails concern, not an Active Record concern. Maybe a fine point of difference, but it's there.

@abhaynikam
Copy link
Contributor

@abhaynikam abhaynikam commented Feb 24, 2019

@dhh : I think we should also add post.not_active? like we already have post.active?. What do you think?

@dhh
Copy link
Member Author

@dhh dhh commented Feb 25, 2019

Not needed. You can always negate a predicate method in a variety of ways with !, unless, and a million other ways. Not so with a scope, thus the need for the help there.

@dhh dhh merged commit 55a7051 into master Feb 26, 2019
0 of 3 checks passed
@dhh dhh deleted the negative-enum-scope branch Feb 26, 2019
suketa added a commit to suketa/rails_sandbox that referenced this issue Aug 31, 2019
Add negative scopes for all enum values
rails/rails#35381
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked issues

Successfully merging this pull request may close these issues.

None yet

2 participants