Daniel
Daniel

Reputation: 3027

Authenticating users

I have a project with several models like students,workers,administrators.... Of course those get different rights on the site.So I was wondering:

Should I log them from different views? so that each one of those views with its forms would handle one (known) model at the time or it would be equally easy to make the three of them in one?.

I tried to make one view but the first problem I had is recognizing which type of user was logging in,therefore it was a problem to know what view should I show next...

Upvotes: 0

Views: 76

Answers (1)

vonconrad
vonconrad

Reputation: 25387

One of the fundamental philosophies behind Rails is DRY--Don't Repeat Yourself. Following this philosophy, it seems rather redundant to have three separate login screens.

In the same vein, having students, workers and administrators in separate models seem a bit unpractical. All users will (presumably) have names, emails and passwords--as well as other information. I would only have one model, and call that model what it is--User. Then, I can set up user groups like this:

class User < ActiveRecord::Base
  belongs_to :user_group
end

class UserGroup < ActiveRecord::Base
  has_many :users
end

User.first.user_group # => <UserGroup name: 'Students'>
User.find(123).user_group # => <UserGroup name: 'Workers'>
UserGroup.find_by_name('Administrators').users # => [<User ...>, <User ...>, ...]

Suddenly, login is no longer a problem. A user is authenticated as a user, and the application will immediately know what user group they belong to, and can display the appropriate information that way.

Also, I'd be amiss if I didn't give a shout-out to Devise. It's a gem for handling authentication, and would definitely spare you a lot of work and effort if you're thinking of creating the authentication methods by yourself.

Upvotes: 1

Related Questions