Co2 Co2 - 1 year ago 81
Ruby Question

Ruby on Rails, Enum user conditions from a different table

I have enums declared as follows in a table separate from my main users table (User.rb). I sign up users and give them a role from this table:


class SchoolUser < ActiveRecord::Base
belongs_to :user
belongs_to :school

enum user_type: [:school, :student, :parent, :teacher]

def school?

def teacher?

def student?

def parent?


I don't think I have to define each role here but I tried it.

I was using a boolean method to separate the users before but switched to enum. I used to use this method type to restrict views based on role:

...unless current_user.teacher?...

This worked fine but now I have the enums declared in a different model to the users table it does not work.

A user has a role through the relationship between user.rb and school_user.rb. This works. I'm just looking for a way to set access based on user role/type in the views as above.

I hope not but I presume I will have to change all the conditions throughout my application?

I tried:

...unless current_user.school_user.teacher?...

and other variations.

Would appreciate any help. Thanks.

Edit: User.rb

class User < ActiveRecord::Base

devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable

validates :first_name, presence:true,
length: {minimum: 4 }
validates :last_name, presence:true

has_many :messages, foreign_key: :sender_id
has_many :notes
has_one :school_user

accepts_nested_attributes_for :school_user

Answer Source

You can delegate this methods to :school_user:

class User < ActiveRecord::Base
  delegate :school?, :student?, :parent?, :teacher?, to: :school_user

Also, remove this methods from SchoolUser class, as mentioned in comments

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download