我有一个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
来获取他保存在所有收藏集中的所有帖子。
但是,我收到此错误
# 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?)
因为集合对象中没有post_id
。
如何获取所有用户收藏集的所有帖子? 谢谢!
答案 0 :(得分:2)
将此添加到User
类
has_many :collected_posts, through: :collections, source: :posts
答案 1 :(得分:1)
我会在用户模型中这样做
def collected_posts
self.collections.map(&:posts).flatten
end
用户拥有收藏集,收藏集拥有帖子(通过帖子收藏集),map函数将在每个收藏集对象上调用该函数并返回帖子。