2016-09-27 45 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)

你不不需要加入