ruby-on-rails - ActiveRecord::HasManyThroughAssociationNotFoundError

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

我有一个用户模型

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/

相关文章:

ruby-on-rails - 创建模型后,searchkick是否会自动更新索引?

ruby - 文件描述符 3 和 4 在 Ruby 中代表什么?

ruby-on-rails - 基于枚举值的自定义顺序

ruby-on-rails - 按钮事件触发

ruby - 拆分字符串而不删除定界符

ruby-on-rails-4 - Rails 模型命名空间依赖销毁导致 mysql 错误未知字段

ruby - 我不明白如何表达三个单独表之间的关系

ruby-on-rails - 如何使用 rails 4.2.7 和 ruby​​ 2.3.3 创建 rails api 项目?

ruby-on-rails - 执行 rake 命令时无法理解 zsh 错误

ruby-on-rails - accepts_nested_attributes_for 验证和使用 find_or_create_by