rails5中如何获取关联的多态对象?

How to get associated polymorphic objects in rails 5?

在我的 Post 模型中,我有

has_many :followers

在我的追随者模型中,我有

belongs_to :model
belongs_to :owner,polymorphic: true

在我的用户和管理员设计模型中,我有

has_many :followers,as: :owner

要求: 我想要 Post.owners 这样的东西,它应该 return 我是所有用户的列表 and/or 管理员在这个 post.

之后

我不确定,但我认为 AR 没有提供一种在一个查询中加载多态关联的方法。但是你可以使用:

post = Post.find(1)
post_followers = post.followers.includes(:owner)
post_owners = post_followers.map(&:owner)

您正在寻找的解决方案是多态的,有很多通过。您可以在用户和管理员模型中添加这些行。

has_many :followers
has_many :posts, through: :followers, source: :owner, source_type: 'Owner'

我想你想要这样的东西:

class Post < ApplicationRecord
  belongs_to :owner, polymorphic: true
end

class User < ApplicationRecord
  has_many :posts, as: :owner
end

class Follower < ApplicationRecord
  has_many :posts, as: :owner
end

从您的用户实例中,您可以使用@user.posts 检索他们的 post 您的关注者也是如此,@follower.posts

如果您想访问 post 实例的父级,可以通过 @post.owner 进行。但是,为了使其工作,我们需要通过在使用引用形式声明多态接口的模型中声明外键列和类型列来正确设置模式:

class CreatePosts < ActiveRecord::Migration[5.0]
  def change
    create_table :posts do |t|
      # your attribs here
      t.references :owner, polymorphic: true, index: true
    end
  end
end