【问题标题】:Many to many through: Going from Associations::CollectionProxy to AssociationRelation多对多通过:从 Associations::CollectionProxy 到 AssociationRelation
【发布时间】:2017-02-01 09:16:20
【问题描述】:

我与偏爱客户的用户建立了多对多关系(通过 favorites.rb),我想知道如何将 CollectionProxy 转换为 AssociationRelation,这样我就可以与所有作为用户的客户建立关系收藏夹。

或者只是简单地说,如何将它们全部放在 AssociationRelation 中 - 不必从 CollectionProxy 中转换。

编辑: 我正在寻找的只是一个列出所有客户的关系。我意识到我提出了不同的问题。 我如何获得与所有客户的关系? - 不是与 favourite_id、user_id 等的关系 - 我想要纯粹与客户及其行的关系。

我可以像这样找到 CollectionProxy:

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

但是我如何找到最喜欢的客户作为 AssociationRelation?

型号:

user.rb:

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

客户端.rb

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

Favorite.rb

belongs_to :user
belongs_to :client

【问题讨论】:

    标签: ruby-on-rails ruby activerecord rails-activerecord ruby-on-rails-5


    【解决方案1】:

    您可以像在 ActiveRecord_AssociationRelation 上一样在 ActiveRecord::Associations::CollectionProxy 上进行操作。

    但如果你真的想要后者,只需拨打电话,例如,all

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

    我如何与所有客户建立关系?

    您已经定义了关联:

    has_many :clients, through: 'favorites'
    

    因此获得关联clients 的关系就像:

    user.clients
    

    【讨论】:

    • 谢谢!这有效地把它变成了一种关系!但也许我的问题并不准确(再次编辑):我正在寻找的是一个关系,我列出了最喜欢的集合中的所有客户。有没有办法只与其中的客户建立关系?不是最喜欢的id,只是客户端。这让我与 favorite_ids 建立了关系。
    • @sneglefar user.clients 就是您要找的。​​span>
    • 但是 user.clients 给了我一个 CollectionProxy? user.clients.count 然后给我 0。有没有办法做 user.clients 并在关系中列出它们?谢谢!
    • 不得不说,我之前一直在使用 favorites.rb 进行多态关联,但没有成功。也许我应该尝试销毁整个模型,然后重新构建它,因为我相信这可能会影响调用 user.clients 的能力 - 非常感谢,它真的很有帮助
    • 重申一下 Andrey 所说的,我将它们映射到 AR 中的方法行不通。它创建了一个 AR,但将订单抛出了窗口
    【解决方案2】:

    伟大的 gem order_as_specified 可以轻松做到这一点!

    1:

    @favorites_collect_the_ids_in_array = @user.favorites.pluck(:client_id) 
    

    ...然后:

    2:

    @ar_of_all_favorites = Client.order_as_specified(id:  @favorites_collect_the_ids_in_array).where(id: @favorites_collect_the_ids_in_array)
    

    【讨论】:

      猜你喜欢
      • 2018-03-02
      • 2016-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多