Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How do you configure an enum in a fixture?

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?

like image 754
Alex Edelstein Avatar asked Mar 26 '15 23:03

Alex Edelstein


People also ask

How to set enum value Rails?

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.

How to add enum column Rails migration?

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!

What is an enum ruby?

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.


1 Answers

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] %>
like image 137
Taryn East Avatar answered Oct 08 '22 04:10

Taryn East