Search code examples
ruby-on-railsruby-on-rails-3authlogicsorcery

Support multiple models with Sorcery or Authlogic gems?


  1. I have users and contacts.
  2. Users sign into their account and can create address books from which they add contacts to.
  3. If they share something with a contact that contact needs to login to view it.

Users are unique in the db (stored in users table) and contacts are stored in the contacts table and are only unique per a given address book.

I'm currently using the Sorcery gem for users, which is working great. However, how can I extend this to support authentication for contact to login?

I've read a bit into doing this via STI or polymorphic setup, but unclear on what the general pattern is for something like this.

Can I simply have both models use Sorcery? Or is that an anti-pattern?

Thanks in advance!


Solution

  • Why are you using a separate model for contacts? Why not just set up a self-join like:

    has_many :contact_entries, :class_name => "ContactEntry"
    has_many :contacts, :through => :contact_entries
    

    Your user table would look the same, but you would have a join model like:

    class ContactEntry < ActiveRecord::Base
      belongs_to :user
      belongs_to :contact, :foreign_key => "contact_id", :class_name => "User"
    end
    

    Which would have a user_id and contact_id field.

    Update

    Okay, I see your issue now. I don't think this will be possible with sorcery, at least not without making substantial edits to sorcery itself. Sorcery defines a single authenticatable model in the file initializer.rb.

    Authlogic, however, can be brought into any model via "acts_as_authentic", so it is a plausible solution to your needs. The drawback is that authlogic doesn't seem to be actively developed. It had a fair amount of activity 10 days ago, however, so it's definitely worth looking in to.