Barkin MAD
Barkin MAD

Reputation: 127

How do I implement Enumerations in my rails app?

Rails version: 4.2.0
OS: Windows 7 (64-bit)

Hello, For example lets say I have a rails app with a posts model.

If I wanted the post model to have a permissions column, which could take on one of several values [public, private, unlisted]

The way I would implement this would be to add a integer column to the posts model, but checking this value would quickly become confusing because I would have to memorize which value corresponds to which permission.

how could I implement an enumeration into this so I could do checks like

if post.visibility == POST_PUBLIC or post.visibility == POST_PRIVATE

Upvotes: 0

Views: 67

Answers (1)

lunr
lunr

Reputation: 5279

Since Rails 4.1 you can have enum attributes in ActiveRecord models. For example:

class Post < ActiveRecord::Base
  enum visibility: [:public, :private, :unlisted]
  ..
end

http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html

Upvotes: 1

Related Questions