2016-09-27 44 views
1

这里是我的两个型号:导轨和哈希语法作用域

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

我在这个范围内搞了些什么?我想在这个范围内保留散列语法。

回答

3

joins/includes可以使用型号名称,但在where条款你应该使用的数据库表名,因而多authors

scope :articles_by_author, lambda { |author_id| 
    joins(:author).where(authors: { id: author_id }) 
} 

附:我已经给你的代码添加了一些符合(Rubocop的)惯例:)

P.P.S.是不是更容易(具有我们知道author_id)只是一起去:

Author.find(author_id).articles # ? :) 
+0

感谢您的回复。你是对的:'Author.find(author_id).articles'可能更好。这只是一个范围练习。谢谢! – Neil

+0

@不客气:) –

2

因为你有一个直的has_many/belongs_to的,你可以做

class Article < ApplicationRecord 
    belongs_to :author 
    scope :articles_by_author, ->(author_id) { where(author_id: author_id) } 
end 

或者Article.where(author_id: author_id)

你不不需要加入