Skip to content

Instantly share code, notes, and snippets.

@skorfmann
Created March 5, 2013 09:47
Show Gist options
  • Select an option

  • Save skorfmann/5089143 to your computer and use it in GitHub Desktop.

Select an option

Save skorfmann/5089143 to your computer and use it in GitHub Desktop.
class Invitation < ActiveRecord::Base
belongs_to :invitable, primary_key: :email, foreign_key: :invitable_id, class_name: 'User'
end
class User < ActiveRecord::Base
has_many :invitations, :primary_key, :email, foreign_key: :invitable_id
end
user = User.create(email: '[email protected]')
invitation = Invitation.create(invitable: user)
invitation.reload
invitation.invitable_id == user.email # false
invitation.invitable_id == user.id # true
@mediafinger
Copy link

Maybe it's the typos in your snippet: :primary_key, :email...? This works for me:

migration:

class UserInvitation < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :email
      t.timestamps
    end

    create_table :invitations do |t|
      t.string :invitable_email
      t.timestamps
    end
  end
end

user.rb:

class User < ActiveRecord::Base
  has_many :invitations, foreign_key: :invitable_email, primary_key: :email

  validates       :email, :presence => true, :uniqueness => true
  attr_accessible :email
end

invitation.rb:

class Invitation < ActiveRecord::Base
  belongs_to :invitable, class_name: 'User', foreign_key: :invitable_email, primary_key: :email

  attr_accessible :invitable
end

in the console:

user = User.create(email: '[email protected]')
invitation = Invitation.create(invitable: user)
invitation.reload

invitation.invitable_email == user.email # true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment