ActiveRecord::HasManyThroughAssociationNotFoundError

ActiveRecord::HasManyThroughAssociationNotFoundError

我有一个User模型

class User < ApplicationRecord
  has_many :posts, dependent: :destroy
  has_many :collections, dependent: :destroy

  # here, I want to get :collected_posts (all posts that all user collections have)
  # has_many :collected_posts, through: :collections, source: :post (this throws error)
end

这是我的Post模型

class Post < ApplicationRecord
  belongs_to :user
  has_many :post_collections, dependent: :destroy
end

这是我的Collection模型

class Collection < ApplicationRecord
  belongs_to :user
  has_many :post_collections, dependent: :destroy
  has_many :posts, through: :post_collections
end

这是我的PostCollection模型

class PostCollection < ApplicationRecord
  belongs_to :post
  belongs_to :collection
end

我想 current_user.collected_posts 获取他在所有 collection 中保存的所有帖子。

但是,我得到了这个错误

# ActiveRecord::HasManyThroughSourceAssociationNotFoundError (Could not find the source association(s) :post in model Collection. Try 'has_many :collected_posts, :through => :collections, :source => <name>'. Is it one of user, post_collections, or posts?)

因为collectionobject中没有post_id

如何获取所有用户 collection 的所有帖子? 谢谢!

我会在用户模型中这样做

 def collected_posts
   self.collections.map(&:posts).flatten
 end

用户有集合集合有 posts(通过 post 集合)映射函数将在每个集合对象和 return posts 上调用该函数.

将此添加到 User class

has_many :collected_posts, through: :collections, source: :posts