这里是我的两个型号:导轨和哈希语法作用域
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
@不客气:) –