Claudiu S
Claudiu S

Reputation: 1627

Rails User - Role relationship with predefined roles?

is there any way when creating migrations to predefine the values an attribute can have?

class User < ActiveRecord::Base
    belongs_to :role
end

class Role < ActiveRecord::Base
    has_many :users
end

and my migrations:

class CreateRoles < ActiveRecord::Migration
  def change
    create_table :roles do |t|
      t.string :name # (regular, admin, etc) => how can we define these as a list?
      t.timestamps
    end
  end
end

class AddRoleToUser < ActiveRecord::Migration
  def change
    add_column :users, :role_id, :integer
  end
end

Upvotes: 0

Views: 276

Answers (1)

pjmorse
pjmorse

Reputation: 9294

One approach is to use a validation like in this question and its two good answers. This validates that the value in a given column is one of a defined list of values. You could either add that validation to your User model and ditch the Role model entirely, or add it to the name field of Role. This is probably the simplest, most Rails-ish way to do it. You could define a constant on your application which contained the approved list of roles, then use whatever works best for you to maintain that list.

Another approach is to make your Role model an ActiveHash model rather than ActiveRecord. ActiveHash lets you set up models which act like ActiveRecord models, but rather than being stored in the database, they're read-only models defined by a hash in the model file. (I'm grossly oversimplifying how ActiveHash works, I expect, but it's a start.) Again, you could use an application constant to maintain the hash.

The advantage to retaining Role as a model is that it allows for Users to have multiple Roles if you ever decided to go that route.

Upvotes: 1

Related Questions