Last active
August 29, 2015 13:56
-
-
Save joekr/9296059 to your computer and use it in GitHub Desktop.
Crazy polymorphic multiple has_many association
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Message < ActiveRecord::Base | |
belongs_to :recipient, :polymorphic => true | |
belongs_to :sender, :polymorphic => true | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
Since User can send and receive messages using
Doesn't work on the model. So I had to alias the j has_many.