我想學習如何編寫範圍在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「是什麼意思」。
任何人都可以看到我需要做的能夠檢查提案表以找到屬於特定用戶的表嗎?
你爲什麼不只是利用協會的你已經做'user.proposals' ? –
因爲我試圖使用Pundit - 它需要範圍。 – Mel
是不是[這個專家](https://github.com/elabs/pundit)?如果是這樣,我不確定是否提到的範圍是軌道範圍。從自述文件中可以看出:「第二個參數是執行某種查詢的某種範圍,它通常是一個ActiveRecord類或一個ActiveRecord :: Relation,但它可能完全是其他類型。」所以使用user.proposals應該沒問題。 –