ActiveRecord :: HasManyThroughAssociationNotFoundError

时间:2018-11-09 15:37:35

标签: ruby-on-rails ruby activerecord associations has-many-through

我有一个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

如何获取所有用户收藏集的所有帖子? 谢谢!

2 个答案:

答案 0 :(得分:2)

将此添加到User

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

答案 1 :(得分:1)

我会在用户模型中这样做

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

用户拥有收藏集,收藏集拥有帖子(通过帖子收藏集),map函数将在每个收藏集对象上调用该函数并返回帖子。