我正在閱讀《Beginning Rails 6 - From Novice to Professional》這本書(很棒的書,順便說一句),我正在閱讀有關 Advanced Active Record 的一章,資訊量很大,但其中的一部分文字讓我發瘋了,它有效,但我沒有得到解釋,有人可以向我解釋一下嗎?
與常規
where方法一樣,您可以使用陣列作為引數。實際上,您可以將 finder 方法與其他命名范圍鏈接。你定義最近的范圍來給你最近發表的文章:首先,你使用published命名的范圍,然后你鏈接到它的 where 呼叫
對我來說,代碼示例并不完全是文本所說的(我試圖找到任何勘誤表,但沒有成功):
class Article < ApplicationRecord validates :title, :body, presence: true
belongs_to :user has_and_belongs_to_many :categories has_many :comments
scope :published, -> { where.not(published_at: nil) }
scope :draft, -> { where(published_at: nil) }
scope :recent, -> { where('articles.published_at > ?', 1.week.ago.to_date) }
def long_title
"#{title} - #{published_at}"
end end
我沒有看到You define the recent scope to give you articles recently published: first, you use the published named scope, and then you chain to it a where call,另外,我不能只使用從 中scope :recent, -> { where('published_at > ?', 1.week.ago.to_date) }洗掉scope :recent, -> { where('articles.published_at > ?', 1.week.ago.to_date) } 嗎articleswhere?
非常感謝!
uj5u.com熱心網友回復:
因此,文本試圖說的是兩件事。一是您可以在其中使用陣列,where并且活動記錄可以理解并將其正確轉換為 SQL。例如Article.where(user_id: [1,2,3]),將查找user_id1、2 或 3 的所有文章。
他們試圖解釋的第二件事是您可以鏈接范圍。所以在這種情況下,他們試圖解釋的是你可以這樣做:Article.recent.published或者Article.recent.draft
對于您的最后一個問題,是的,您可以按照您的建議撰寫它并且它會起作用:recent, -> { where('published_at > ?', 1.week.ago.to_date) }。他們使用的原因articles.是當您嘗試使用連接鏈接作用域時確保作用域有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/484149.html
下一篇:姜戈|獲取每月文章數
