Search code examples
ruby-on-railsrubyactiverecordruby-on-rails-5ruby-on-rails-6

Many to many through: Going from Associations::CollectionProxy to AssociationRelation


I have a many to many through relationship with users favoriting clients (Through favorites.rb) and I want to know how to turn a CollectionProxy into an AssociationRelation, so I can get a relation with all the clients that are the users' favorites.

Or just simply, how to get them all in a AssociationRelation - doesn't have to be turned into from the CollectionProxy.

EDIT: What I'm looking for is simply a relation that lists all the clients. I realize I asked the question differently. How do I get a relation with all the clients? - Not a relation with the favorite_id, user_id, etc - I want a relation purely with the clients, and their rows.

I can find the CollectionProxy like this:

user = User.last
user.favorites    # Gives me a CollectionProxy

But how do I find the favorite clients as an AssociationRelation?

Models:

user.rb:

has_many :favorites, :dependent => :destroy
has_many :clients, through: 'favorites'

Client.rb

has_many :favorites, :dependent => :destroy
has_many :users, through: 'favorites'

Favorite.rb

belongs_to :user
belongs_to :client

Solution

  • You can operate on ActiveRecord::Associations::CollectionProxy as you would normally do on ActiveRecord_AssociationRelation.

    But if you really want to have the latter, just call, for example, all:

    user.favorites.all.class #=> Client::ActiveRecord_AssociationRelation
    

    How do I get a relation with all the clients?

    You have defined the association:

    has_many :clients, through: 'favorites'
    

    Thus getting a relation of associated clients is as easy as:

    user.clients