问题
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
回答1:
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
回答2:
The great gem order_as_specified can do this in an easy manner!
1:
@favorites_collect_the_ids_in_array = @user.favorites.pluck(:client_id)
... then:
2:
@ar_of_all_favorites = Client.order_as_specified(id: @favorites_collect_the_ids_in_array).where(id: @favorites_collect_the_ids_in_array)
来源:https://stackoverflow.com/questions/41975930/many-to-many-through-going-from-associationscollectionproxy-to-associationrel