【发布时间】:2021-09-21 01:24:25
【问题描述】:
我目前正在尝试实现一个 has_one 关系,您可以在其中搜索所有博客的活动帖子。我的问题出在即使我明确搜索 active_post 关系,它也会返回其帖子中的所有内容,而不仅仅是我想要的活动帖子。
# == Schema Information
#
# Table name: blog
#
# id :integer not null, primary key
# name :string(200)
# context :string(20)
# show_on_summary :boolean
#
class Blog < ApplicationRecord
has_many :posts, dependent: :destroy, autosave: true
has_one :active_post, -> { order('created_at DESC').where(posts: { status_code: 'active' }) }, class_name: 'Post', foreign_key: :blog_id
# == Schema Information
#
# Table name: posts
#
# id :integer not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
# status_code :string(20)
# blog_id :integer
#
class Post < ApplicationRecord
STATUS_CODES = %w(active pending deactivated)
belongs_to :blog
然而,当我运行下面的代码时,我有一个任何类型的 status_code 的帖子列表,并试图找到只有他们的 active_post 关系匹配的博客,它会返回每个在该列表中有帖子的博客,不管status_code。
Blog.where(active_post: list_of_posts)
当我调试时,我可以去各个博客查看他们的“active_post”关系,它会显示正确的最新活动帖子。如果没有活动帖子,它将返回 nil,这正是我想要的。
【问题讨论】: