2013-04-27 19 views
0

我在task.rb下面的代碼時收到錯誤:Rails的使用REST來輸入數據

before_update :update_inspector 

    protected 
    def update_inspector 
    self.inspector_id = User.current.employee.id 
    end 

它工作正常。

但是,我希望能夠使用REST更新任務。所以,使用REST時不會有當前用戶。

所以,我嘗試這樣做:

before_update :update_inspector, :unless => User.current.employee.id.empty 

    protected 
    def update_inspector 
    self.inspector_id = User.current.employee.id 
    end 

但是,這是行不通的。

我ASLO嘗試:

:unless => User.current.employee.id = nil 

感謝您的幫助!

UPDATE1

我也試過這樣:

before_update :update_inspector 

protected 
def update_inspector 
    self.inspector_id = User.current.employee.id unless User.current.employee.id.nil? 

end 

UPDATE2

我能夠訪問User.current.employee.id,因爲這是我user.rb:

def self.current 
    Thread.current[:user] 
end 
def self.current=(user) 
    Thread.current[:user] = user 
end 

UPDATE3

我最後一次嘗試給了我這個:

> undefined method `employee' for nil:NilClass 

app/models/task.rb, line 30 
--------------------------- 

``` ruby 
25 
26  before_update :update_inspector 
27 
28  protected 
29  def update_inspector 
> 30  self.inspector_id = User.current.employee.id unless User.current.employee.id.nil? 
31 
32  end 
33 
34 end 
+0

在不工作的情況下,我假設你是update_inspector方法仍然被調用。你能記錄User.current.employee的實際值嗎?由於這看起來是一種類方法,它是否從先前的請求中懸掛下來? – Phil 2013-04-27 18:42:04

+0

定義「沒有工作。」什麼是'User.current'?當沒有當前用戶時是否設置?例如,你的條件在它到達'employee'(或'employee.id')之前拋出一個錯誤?我們看不到您的代碼。 – 2013-04-27 18:42:07

+0

嘗試:'empty?'或'=='而不是'empty'或'=' – Zippie 2013-04-27 18:47:54

回答

0

如果你希望那裏是當前用戶在某些情況下,你不能叫User.current.employee可言,因爲User.currentnil,導致這種錯誤:

undefined method `employee' for nil:NilClass

如何:

before_update :update_inspector 

protected 
def update_inspector 
    self.inspector_id = User.current.employee.id unless User.current.nil? 
end 

臨屋t方式,如果User.currentnil,您甚至不會嘗試調用.employee方法。你可以進一步優化,通過使用employee_id,而不是employee.id避免Employee記錄的數據庫查詢:

self.inspector_id = User.current.employee_id unless User.current.nil? 
+1

感謝您的幫助! – Reddirt 2013-04-27 19:08:35

0

的問題是,User.currentnil。嘗試訪問超出該點的任何方法將導致錯誤,因爲employee不是在NilClass上定義的方法。你應該改變你的條件:

before_update :update_inspector, :if => lambda { User.current } 
+0

我不認爲這會起作用,因爲':if'的值需要是符號,字符串或Proc,所以它可以被多次評估。請參閱http://guides.rubyonrails.org/active_record_validations_callbacks.html#conditional-callbacks – 2013-04-27 22:07:41

+0

好的結果。固定。 – davogones 2013-04-27 22:56:38