2015-05-05 44 views
1

我在類中有以下方法,我需要從另一個模型中拉出一個項目以用於此方法。我似乎無法拉項目,因爲我正在使用current_user來獲取其他項目,並且該模型無法識別current_user。我不知道這是幹什麼,因爲我已經讀過模型不應該調用current_user。這裏是方法...從另一個模型獲取對象的方法

class Upsell 
    include Mongoid::Document 
    belongs_to :user 
    belongs_to :charges 

... 

    def total_fees 
    items = [] 
    items << (current_user.reportapprovals.first.admin_request_report_type).to_i 
     if self.multiple_admin == true 
     items << self.multiple_admin_amount 
     end 
end 

我的錯誤是,

undefined local variable or method `current_tenant' for #<Upsell:0xc82c9d39> 

我想知道如果我要設置用戶在模型中,但到目前爲止還沒有工作。

@user = User.find(params[:id]) 
+1

如果你有** **的用戶相關的** **向上銷售,那麼你可以調用'self.user'而不是** current_user **否則你必須將它作爲參數傳遞給函數。而且你永遠不會在你的模型中得到params,所以這個 - >'User.find(params [:id])'行不起作用。 – Abhi

+1

通常情況下,current_user是存儲在application_controller中的輔助方法,它不能從任何模型訪問。也許你可以使用'self.user.reportapprovals ...''current_user.reportapprovals ...' –

回答

3

您需要通過current_user作爲函數參數

def total_fees_for user 
    items = [] 
    items << (user.reportapprovals.first.admin_request_report_type).to_i 
    if self.multiple_admin == true 
     items << self.multiple_admin_amount 
    end 
end 
+0

''哇,這就是它!實際上我比它更困難。 – SupremeA

相關問題