Skip to content

Add negative scopes for all enum values - #35381

Merged
dhh merged 3 commits into
masterfrom
negative-enum-scope
Feb 26, 2019
Merged

dhh merged 3 commits into
masterfrom
negative-enum-scope

Conversation

@dhh

@dhh dhh commented Feb 23, 2019

Copy link
Copy Markdown
Member
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]).

Comment thread activerecord/CHANGELOG.md Outdated

Example:

class Post < ActiveRecord::Base

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
Copy Markdown
Contributor

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

@dhh

dhh commented Feb 25, 2019

Copy link
Copy Markdown
Member Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants