2016-12-17 40 views
2

我想學習如何編寫範圍在Rails的5Rails的5 - 如何寫一個範圍

我有一個用戶模型和建議的模式。該協會是:

用戶:

has_many :proposals 

建議:

belongs_to :user 

在我的提議模型,我試着去弄清楚如何寫的涵蓋範圍認定,屬於用戶的建議創造它們。

我想:

scope :proponent, -> { where(user_id: user.id) } 

我試圖在這上百萬的變化,但我無法找到一個工程。

這種特殊的嘗試給出了這樣的錯誤:

2.3.1p112 :001 > Proposal.proponent 
NameError: undefined local variable or method `user' for Proposal (call 'Proposal.connection' to establish a connection):Class 

我也試過:

scope :proponent, -> { where('proposal.user_id = ?', user.id) } 

我從這個嘗試得到的錯誤是:

undefined local variable or method `user' for #<Class:0x007fd3600eb038> 

我不知道錯誤消息是否意味着我在第一次或第二次寫入'用戶'時出現錯誤。我不知道「呼叫」Proposal.connection「是什麼意思」。

任何人都可以看到我需要做的能夠檢查提案表以找到屬於特定用戶的表嗎?

+0

你爲什麼不只是利用協會的你已經做'user.proposals' ? –

+0

因爲我試圖使用Pundit - 它需要範圍。 – Mel

+0

是不是[這個專家](https://github.com/elabs/pundit)?如果是這樣,我不確定是否提到的範圍是軌道範圍。從自述文件中可以看出:「第二個參數是執行某種查詢的某種範圍,它通常是一個ActiveRecord類或一個ActiveRecord :: Relation,但它可能完全是其他類型。」所以使用user.proposals應該沒問題。 –

回答

4

當您調用範圍時,您需要將useruser_id作爲參數通過。你可以這樣定義它:

scope :proponent, ->(user){ where(user_id: user.id) } 

def self.proponent(user) 
    where user_id: user.id 
end 

這真的是同一件事。

然後調用它:

Proposal.proponent(user) 
# => returns a list of proposals for the specific user 

注意,這是同樣的事情,說

proposal = Proposal.find_by(...) 
proposal.user.proposals 
+0

按照您的建議嘗試範圍時,出現如下錯誤:錯誤的參數數量(給定0,預計爲1) – Mel

+0

當我嘗試按照您寫入的方式更改範圍時,出現同樣的錯誤第一組()內的「user_id」() – Mel

+0

@Mel第一個錯誤意味着你說'Proposal.proponent'而不是'Proposal.proponent(user)'。 –