简体   繁体   中英

How do I specify 2 foreign keys in a model in ruby on rails?

I'd like to be able to access current_users conversation with ease. EG

current_user.conversations

The thing is the current user can either be a sender or recipient (sender_id or recipient_id)

class User < ActiveRecord::Base

  has_many :conversations, :foreign_key => "sender_id"

This works but there are times when a sender is a recipient or say for example someone has sen t someone 10 messages as a sender and the recipient hasn't replied to any but still a conversation exists in the database for them.

If I was logged in as that user and typed current_user.conversations nothing would come up because the foreign key specified in the user model is sender_id. Isn't there a way to specify both? Like using "OR" in sql?

Kind regards

I don't believe there is a way to do exactly what you want, but there are a few alternate approaches you may want to consider:

1) Splitting it up into two relationships, sent_conversations and received_conversations, and then you can define a method which combines them.

2) Adding a new class method that does some custom SQL:

class User < ActiveRecord::Base
  def conversations
    Conversation.where("sender_id = :id OR receiver_id = :id", id: self.id)
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM