【问题标题】:Ruby finding all objects where has_one relation is true and is in arrayRuby 查找 has_one 关系为真且在数组中的所有对象
【发布时间】: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,这正是我想要的。

【问题讨论】:

    标签: ruby has-one


    【解决方案1】:

    如果不手动加入表格,我认为您无法做到这一点

    Blog.joins(:active_post).where(posts: { id: list_of_posts })
    

    当你加入你的表时,你确保该关系将被使用,并指定“posts”.“id”列也确保它不会使用子查询来匹配博客 id

    【讨论】:

    • 所以在这种情况下,我仍然遇到同样的问题,它将返回所有活动帖子的结果。
    • 你能举例说明你期望返回什么吗?没看懂
    【解决方案2】:

    我认为你不需要在 where 子句中指定 :posts 表:

    class Blog < ApplicationRecord
      has_many :posts, dependent: :destroy, autosave: true
      has_one :active_post, -> { order('created_at DESC').where(status_code: 'active') }, class_name: 'Post', foreign_key: :blog_id
    #...
    end
    
    
    Blog.first.active_post
    # => return the latest post
    

    【讨论】:

    • .where 语句存在同样的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    相关资源
    最近更新 更多