0

I have this:

collectedclientids = user.favorites.pluck(:client_id)

and it gives me this:

=> [18, 34, 1, 90]

Now, I want to fetch clients in the exact same order and have an array with them, or an ActiveRelation.

It'd be similar in ruby to do this:

clientsordered = collectedclientids.each_with_object([]) { |id, array| array << Client.find(id) } 

.. which gives me an array of the clients in the same order with client_id [18, 34, 1, 90]

But how can I accomplish this in rails? Any ideas on methods to use?

Ursus
  • 29,643
  • 3
  • 33
  • 50
sneglefar
  • 117
  • 9
  • 1
    In the linked question there are answers for two major databases: [postgresql](http://stackoverflow.com/a/33651683/1772830) and [mysql](http://stackoverflow.com/a/1685784/1772830) – Andrey Deineko Feb 01 '17 at 12:13
  • @AndreyDeineko I don't think this is a duplicate. The problem should be solved by using a `through` relationship on the `Favourite` object. That is, within `User`, there should be `has_many :clients, through: :favourites`. With that in place @sneglefar will be able to do `user.clients` and `user.clients.pluck(:id)` – ReggieB Feb 01 '17 at 13:18
  • @ReggieB [OP already has this setup](http://stackoverflow.com/questions/41975930/many-to-many-through-going-from-associationscollectionproxy-to-associationrel), but it is (at least that's what he claims) somehow broken. – Andrey Deineko Feb 01 '17 at 13:19
  • OK - then I agree - this is a duplicate. – ReggieB Feb 01 '17 at 13:20
  • Thanks Andrey. It is a duplicate in that case. The original thread, suggests 3 things: 1) To get them as an array (not AR), 2 ) To get an AR, based on an advanced scope I do myself and 3 ) using a gem called order_as_specified. I have now tried 1 and 3, and 3 doesn't work for me (Rails 5). 1 works, and I can get an array, but I want an AR. I've also tried a bit with scopes (2) in Rails 5, but it seems as if scopes in rails 5 are not the way to go? Any other ways or easier explained ways to get an AR with the clients? (An easier explanation of 2) – sneglefar Feb 01 '17 at 13:32

0 Answers0