ruby-on-railsactiverecordactive-relation

How to combine two ActiveRecord::Relation to form active relation under OR condition?


This link is great but it doesn't address the problem of getting an active_relation after combining two active relation under or condition. There are other links as well but
none of them answer the above question. Although for anding method merge works and gives active relation, my predicament in finding a way to or two condition. To elucidate my problem, suppose I have to or two differently written query rather than performing separately and adding them which does not output active relation. For example:-

@incoming = Message.incoming_from_my_friends_only(@current_user) # where 'incoming_from_my_friends_only' is a active record query  
@outgoing = Message.outgoing_to_my_friends_only(@current_user) # same here

Now, I don't want to do this

@incoming = Message.incoming_from_my_friends_only(@current_user) 
@outgoing = Message.outgoing_to_my_friends_only(@current_user)

@messages = @incoming + @outgoing

Although doing this is not an issue, but I would rather have the result in active relation so that I can perform any further active record query.

Any ideas... or better work around for my problem??

Revised:-

I was looking at the profile and found that this question was bereft of any activity, not even a comment, even though it might prove to be question vital importance. I saying this because doing and on AR is very easy as shown in second link using merge method but no such method exist for or why is that??? shouldn't the pro of rails community provide this method???


Solution

  • I later found a way to combine two active relation under or condition but not the answer I was looking for like- there is method for performing and on active relation using merge. Answer I found was this.

    # replace the comment part in where by the condition written for incoming_from_my_friends_only and outgoing_to_my_friends_only respectively
    @incoming = Message.where("(#incoming_from_my_friends_only(@current_user)) or (outgoing_to_my_friends_only(@current_user))")