NoamB/sorcery — Issue #116: Why do classes that inherit from User still need `authenticates_with_sorcery!`?
Author: sumeetjain
Created: 2011-10-27 02:54:42+00:00
State: open

I prepared a basic Rails app to demonstrate the cause of my confusion: https://github.com/sumeetjain/sorcery-sti-example

### Basic App with Sorcery

`User` is generated with `rails generate sorcery:install`:

```ruby
# user.rb
class User < ActiveRecord::Base
authenticates_with_sorcery!
end
```

### Single Table Inheritance

I also add a `type` column to the `users` table, which I'll use to achieve Single Table Inheritance with soon-to-be-added subclasses.

The subclasses are `Doctor` and `Patient`. They have no tables, since they inherit from `User`.

### How It Works

I should be able to **create a User** by passing a username and password in Rails Console, like so:

```ruby
User.create({:username => "foo1", :password => "bar"})
```

And I should be able to **create a new Doctor or Patient** by passing an additional property called `type`, like so:

```ruby
User.create({:username => "foo2", :password => "bar", :type => "Doctor"})
```

So when I run `User.all`, I get back two Users - one of which is a Doctor. And when I run `Doctor.all`, I get back one user.

That all works as expected.

### Problem

But I should also be able to create a Doctor or Patient in Rails Console, like so:

```ruby
Doctor.create({:username => "foo3", :password => "bar"})
Patient.create({:username => "foo4", :password => "bar"})
```

This fails, and I get the error:

`NoMethodError: undefined method 'password_attribute_name' for nil:NilClass`

The subclasses look like this:

```ruby
# doctor.rb
class Doctor < User
end

# patient.rb
class Patient < User
end
```

Which I thought would be sufficient. But I can only create a Doctor or Patient from Rails Console when I add `authenticates_with_sorcery!` to them:

```ruby
# doctor.rb
class Doctor < User
authenticates_with_sorcery!
end

# patient.rb
class Patient < User
authenticates_with_sorcery!
end
```

And that just seems strange - to have to repeat the method call like that.

Thoughts?