Check my website: www.alexandrecalaca.com.br
- 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
- 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.
- Run the migration
rails db:migrate
- 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
- 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}
- 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">
- 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!
- You can also ask if a record has a X status. You have an item selected first.
Blog.last.published?
- Create a custom route