Given this class:
class User < ActiveRecord::Base
enum permission: {
permission_user: 1,
permission_staff: 2,
permission_manager: 3,
permission_admin: 4,
permission_super_admin: 5
}
I want to create a fixture that looks like this:
testuser1:
id: 1
username: sam
permission: :permission_staff
I've tried a number of variations of syntax, but haven't found something that works. the resulting user.permission is either nil or 0. I know that enum is relatively recent addition. Can this be done?
Instead, we can add prefix and suffix as per our requirement and call the methods accordingly. # app/models/post. rb class Post < ActiveRecord::Base enum :status, { draft: 0, published: 1, archived: 2, trashed: 3 }, prefix: true enum :category, { free: 0, premium: 1 }, suffix: true end Post. free_category post.
First of all, you need to create an appropriate migration. Notice that column type is set to integer and this is how Rails keeps enums values in the database. Next step is to declare enum attribute in the model. Run the migrations and that's it!
Ruby on Rail's ships with a module known as Enum which has a parent class of ActiveRecord . This handy module allows you to declare different states in the database using any Model in your Rails application. Enums are powerful thanks to the built-in methods and scopes that come with the framework.
According to the enum docs you can refer to the enumerable through the class like this:
User.permissions[:permission_staff]
And the factories are just ruby code - so they should be able to access the value in the same way
testuser1:
id: 1
username: sam
permission: <%= User.permissions[:permission_staff] %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With