【问题标题】:Get children of three different parents in polymorphic association在多态关联中获取三个不同父母的孩子
【发布时间】:2016-03-05 18:14:02
【问题描述】:

我有模型Post,通过多态性属于OrganizationTeamUser

对于每个家长,我都在获取这样的帖子:

current_user.posts
current_user.organization.posts
current_user.team.posts

如何将这些返回单个 AR 对象的查询与所有帖子合并?

我尝试了以下方法:

Post.where(trackable: current_user).where(trackable: current_user.team) # returns 0 objects

current_user.posts + current_user.organization.posts # this returns an array

【问题讨论】:

  • 您是否尝试过类似:Post.where(trackable: [current_user, current_user.organization, current_user.team])
  • 有效!实际上我现在发现我也可以使用 Rails 5 new .or like Post.where(trackable: current_user).or(Post.where(trackable: current_user.team))。但是按照您的建议将它们放在一个数组中会更干净。谢谢!
  • 太棒了。很高兴它奏效了。我将其发布为答案,以便您接受。

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


【解决方案1】:

这应该可以解决问题:

Post.where(trackable: [current_user, current_user.organization, current_user.team])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多