I’m learning Ruby on Rails through Micheal Hartl’s tutorial.
In my web application, I require two types of Users, called publishers and subscribers. Currently I have a publishers resource and a subscribers resource. I’d like both of them to be able to use the sessions resource for signin/signout.
I’m looking for some direction on how to implement this. Should my publisher and subscriber resource inherit from the User resource, so that, for example, the following code works through polymorphism?
def create
user = User.find_by_email(params[:session][:email])
if user && user.authenticate(params[:session][:password])
# Sign the user in and redirect to the user's show page.
else
# Create an error message and re-render the signin form.
end
end
The publisher and subscriber do not have many common fields and different capabilities, so I think they should be modeled as two separate resources, but how to have them share the Sessions resource?
One possible solution is to make the User class be used only for login and the user would belong to a Publisher or Subscriber via a polymorphic association, as in:
If you don’t know what polymorphic associations are, you should read this tutorial.
This code would be used like this:
So, your Subscriber or Publisher is going to be related to one user, the :identifiable field is a relationship (a polymorphic relationship) to another object.
With this a user could use this identifiable association to be a Subscriber or a Publisher and your SessionsController would be reused for both of them (and all the authentication logic too, since it would live inside of User and not these other classes).