extracted piece of code into a method

In order to fix #10421 I need to enable merge to take an option
so that relations could be merged without making the last where
condition to win.

That fix would forever reside in 4-0-stable branch and would not be
merged to master since using scope without lambda has been deprecated.

In this commit I have extracted code into a method and I think it
makes code look better. Hence the request to merge it in both
master and 4-0-stable.

If there is any concern then this code can be merged only in
4-0-stable and that would be fine too.
Merge pull request #10523 from neerajdotname/last-where-clause-wins

Extraction to enable fixing #10421
Fix that JSON and XML exception responses should give the HTTP error message for their status, by default, not the message from the underlying exception
"rails" -> "Rails" [ci skip]
rails -> Rails [ci skip]
Merge pull request #10532 from prathamesh-sonpatki/Rails

rails -> Rails [ci skip]