- Short Ruby Newsletter
- Posts
- How to use Postgres Enums with Rails 7
How to use Postgres Enums with Rails 7
#codesummary #code #summary #rails #rails7 #postgresql #enums
This is a code summary for https://allaboutcoding.ghinda.com/how-to-work-with-postgresql-enums-in-rails-7
![# Part 1/3: How to create an enum type for an Active Record Model def up create_enum :user_status, ["pending", "active", "archived"] # creating enum type create_table :users, force: true do |t| t.enum :status, enum_type: "user_status", default: "pending", null: false end end def down drop_table :users execute <<-SQL DROP TYPE user_status; SQL end # This is how the model might look like when using standard Rails class User < ActiveRecord::Base enum status: { pending: 'pending', active: 'active', }, _prefix: true end # the following queries will work User.status_pending.count user.status_pending?](https://media.beehiiv.com/cdn-cgi/image/fit=scale-down,format=auto,onerror=redirect,quality=80/uploads/asset/file/ea226ff2-ae52-4b4a-8384-705dfff91eb9/3f6e6965-f42e-4610-9055-1e8647493106_1406x1252.png?t=1726892711)


If you want to play with the code, I create a single file Rails app here: postgres_enums_in_rails_7.rb
Reply