我目前正在嘗試實作一個has_one關系,在這個關系中,你可以通過所有的博客活動帖子進行搜索。我的問題是,即使我明確地通過active_post關系進行搜索,它也會回傳其帖子中的所有內容,而不僅僅是我想要的活躍帖子。
# == Schema Information.
#
# Table name: blog
# # 表名: blog
# id :integer not null, primary key
# name :string(200)
# context :string(20)
# show_on_summary :boolean。
#
class Blog < ApplicationRecord
has_many :post, 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
# # 表名: posts
# id :integer not null, primary key
# created_at :dateetime not null
# updated_at :dateetime not null
# status_code :string(20)
# blog_id :integer
#
class Post < ApplicationRecord
STATUS_CODES = %w(active pending deactivated)
belongs_to :blog。
然而,當我運行下面的代碼時,我有一個任何型別的狀態代碼的帖子串列,并試圖找到只有它們的active_post關系相匹配的博客,它將回傳該串列中的每一個有帖子的博客,無論狀態代碼如何。
Blog.where(active_post: list_of_posts)
當我除錯的時候,我可以進入各個博客并查看他們的'active_post'關系,它將顯示正確的最新活動帖子。如果沒有活動帖子,它將回傳nil,這是我想要的。
uj5u.com熱心網友回復:
我不認為你可以在不手動加入你的表的情況下做到這一點
Blog.joins(:active_post).where(posts:/span> { id: list_of_posts })
當你加入你的表時,你確保關系將被使用,指定 "posts". "id "列也確保它不會使用子查詢來匹配 Blogs ids
uj5u.com熱心網友回復:我認為你不需要在where子句中指定:post表:
class Blog < ApplicationRecord
has_many :post, 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
# => 回傳最新的帖子。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/323808.html
標籤:
