Skip to content

Instantly share code, notes, and snippets.

@alexcalaca
Last active May 29, 2018 22:58
Show Gist options
  • Save alexcalaca/c64c36abe8a189f97eb08b1dc56529de to your computer and use it in GitHub Desktop.
Save alexcalaca/c64c36abe8a189f97eb08b1dc56529de to your computer and use it in GitHub Desktop.
How to use enums in Rails

Check my website: www.alexandrecalaca.com.br

  1. First of all, let's generate a migration that it is going to add a status attribute to the table.
rails generate migration add_post_status_to_blogs status:integer
  1. Open the migration you have just created. Your code needs to be something like this:
def change
    add_column :blogs, :status, :integer, default: 0
  end

We need a default value when we're using enums in Rails.

  1. Run the migration
rails db:migrate
  1. Open the schema.rb file and see if the status attribute is there. Inside the blogs table, you need to have this line:
    t.integer  "status",     default: 0
  1. Add this line to your model.rb file. In my example, "status" is the attribute that you just created when you ran the migration. You're able to choose your own enum values.
enum status: {draft: 0, published: 1}
  1. In order to test, go to rails console and create a blog post.
rails console
log.create!(title: "My post", body: "My body")                                                                                                        

Now, you're able to see the default value for status.

=> #<Blog id: 23, title: "My post", body: "My body", created_at: "2018-05-29 02:51:04", updated_at: "2018-05-29 02:51:04", slug: "my-post", status: "draft"> 
  1. If you want to change the status value, just run of the key values created in the model file with an exclamation mark.
Blog.last.draft!
Blog.last.published!
  1. You can also ask if a record has a X status. You have an item selected first.
Blog.last.published?
  1. Create a custom route
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment