我有一个用户
模型
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
这是我的集合
模型
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
。
如何获取所有用户收藏的所有帖子? 谢谢!
最佳答案
将此添加到 User
类
has_many :collected_posts, through: :collections, source: :posts
关于ruby-on-rails - ActiveRecord::HasManyThroughAssociationNotFoundError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53228803/