1

I'm using MySQL and I'm trying to create a couple of scopes to find a User based on a set of conversations, users and conversations have a polymorphic association that allows the user to author and receives conversations.

The "with_conversations" scope is doing what I want, however, it's not very efficient, I'm having trouble making it execute a single query instead of the addition 2 arrays, which triggers 2 separate queries.

class User 

  scope :with_received_conversations, -> (conversations) { joins(:received_conversations).where(conversations: { id: conversations, receiver_type: "User" }) }
  scope :with_authored_conversations, -> (conversations) { joins(:authored_conversations).where(conversations: { id: conversations, author_type: "User" }) }
  scope :with_conversations,          -> (conversations) { with_authored_conversations(conversations) | with_received_conversations(conversations) }

end

I attempted using the "or()" active record function but it returns the following error:

*** ArgumentError Exception: Relation passed to #or must be structurally compatible. Incompatible values: [:joins]

nil
Alvaro Alday
  • 343
  • 3
  • 19
  • using || instead of | can return an empty array when the authored_conversations are empty, but the received conversations are not. this is an example of this occurring in one of my tests. `with_received_conversations(conversations) || with_authored_conversations(conversations) ` `#` – Alvaro Alday Sep 24 '19 at 16:20
  • Would you mind adding your models? And the db/schema file if needed? – Sebastián Palma Sep 24 '19 at 18:47
  • `scope` is just syntactic sugar for declaring class methods. Its best used for simple one-liners (that actually fit on a normal line). Use normal class method definition on these monsters for better readability. – max Sep 24 '19 at 19:15
  • 1
    This might be helpful for you: https://stackoverflow.com/questions/6686920/activerecord-query-union – Akshay Goyal Sep 25 '19 at 07:18

1 Answers1

0

I'm not allowed to comment so I am sorry for creating an answer. I think that this post is helpful.

Relation passed to #or must be structurally compatible. Incompatible values: [:references]

zakariah1
  • 362
  • 1
  • 11