這裏是我的兩個型號:導軌和哈希語法作用域
class Author < ApplicationRecord
has_many :articles
end
class Article < ApplicationRecord
belongs_to :author
scope :articles_by_author, ->(author_id) {joins(:author).where(author: {id: author_id})}
end
我試圖讓Article.articles_by_author(id)
範圍工作。基本上:它應該返回特定作者的所有文章。
這裏是發生了什麼:
首先我抓住作者:
author = Author.first
然後我運行查詢:
Article.articles_by_author(author)
生成的SQL似乎是正確的:
SELECT "articles".*
FROM "articles"
INNER JOIN "authors"
ON "authors"."id" = "articles"."author_id"
WHERE "author"."id" = 1
但它錯誤o UT有以下:
的ActiveRecord :: StatementInvalid:SQLite3的::的SQLException:沒有這樣的列:author.id:選擇 「物品」 * FROM 「文章」 INNER JOIN 「作者」 ON 「作家」「。 id「=」articles「。」author_id「WHERE」author「。」id「= 1
我在這個範圍內搞了些什麼?我想在這個範圍內保留散列語法。
感謝您的回覆。你是對的:'Author.find(author_id).articles'可能更好。這只是一個範圍練習。謝謝! – Neil
@不客氣:) –