Skip to content

Instantly share code, notes, and snippets.

@joekr
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joekr/9296059 to your computer and use it in GitHub Desktop.
Save joekr/9296059 to your computer and use it in GitHub Desktop.
Crazy polymorphic multiple has_many association
class Message < ActiveRecord::Base
belongs_to :recipient, :polymorphic => true
belongs_to :sender, :polymorphic => true
end
class User < ActiveRecord::Base
has_many :messages_as_received, -> { where("recipient_type = 'User'") },
:foreign_key => "recipient_id", :class_name => "Message"
has_many :received_messages, :through => :messages_as_received, :source => :recipient, :source_type => "User"
has_many :messages_as_sent, -> { where("sender_typ = 'User'") },
:foreign_key => "sender_id", :class_name => "Message"
has_many :sent_messages, :through => :messages_as_sent, :source => :sender, :source_type => "User"
end
@joekr
Copy link
Author

joekr commented Mar 1, 2014

Since User can send and receive messages using

 has_many :messages, :as => :recipient
 has_many :messages, :as => :sender

Doesn't work on the model. So I had to alias the j has_many.

@rlmattax
Copy link

rlmattax commented Mar 1, 2014

This all looks like what I was expecting. Good job.

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