has_many association with two foreign keys

Hello,

I was wondering if there is a way to specify two foreign keys on a has_many association. I have a conversation model with a sender_id and recipient_id. A user can be the sender or recipient of a conversation. To fetch all conversations I must specify the sender_id and recipient_id on the User model, but I can only specify one of the two as shown below.

class User < ActiveRecord::Base   has_many :conversations, :foreign_key => 'sender_id' end

Is there any way to specify two foreign keys?

Thanks!

I don't think there is...

but if you need to encompass that in a single AR association, you could changed the table design to:

Users

UserConversations user_id conversation_id participation_type

Conversations

then you could have several different through associations from user to conversation, with or without participation_type.

JDevine wrote:

I don't think there is...

but if you need to encompass that in a single AR association, you could changed the table design to:

Users

UserConversations

That should be called Participations or something.

user_id conversation_id participation_type

Conversations

then you could have several different through associations from user to conversation, with or without participation_type.

Best,

Elias Orozco wrote:

Hello,

I was wondering if there is a way to specify two foreign keys on a has_many association. I have a conversation model with a sender_id and recipient_id. A user can be the sender or recipient of a conversation. To fetch all conversations I must specify the sender_id and recipient_id on the User model, but I can only specify one of the two as shown below.

class User < ActiveRecord::Base   has_many :conversations, :foreign_key => 'sender_id' end

Is there any way to specify two foreign keys?

Sure! You can have two separate associations between the same tables -- or follow JDevine's suggestion.

Thanks!

--

You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk@googlegroups.com. To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com. For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

Best,

another cool way would be to say

has_many :conversations, :foreign_key => ‘sender_id’, :conditions => ‘recipient_id = #{id}’

make sure to use single quotes here, or it won’t evaluate the #{}

@ChrisDrappler The problem with this approach is that the conditions params add an AND to the query and it should be an OR.

What you suggest does the following:

SELECT * FROM `conversations` WHERE (`deals`.sender_id = 3 AND (recipient_id = 3))

And it should be:

SELECT * FROM `conversations` WHERE (`deals`.sender_id = 3 OR (recipient_id = 3))