2017-09-16 128 views
1

副記錄我加了一個自定義的設計會話控制器記錄相關聯的人登錄後:設計:在登錄

class SessionsController < Devise::SessionsController 

    before_create :associate_calculation 

    def associate_calculation 
     Calculation.find(self.calculation_id).user_id = self.id 
     Calculation.last.save! 
    end 

end 

這裏是請求參數:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"JOQQcCTB9tkVegDgHP/ww8hu5qSzNWlu+4HZZ9AmQGYVO60f3BliwEYT+HKAGPsOOqbipSgj/xSqcDLqueOPZw==", "user"=>{"calculation_id"=>"48759708645478633", "email"=>"[email protected]", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Signin"} 

我還添加attr_accessor :calculation_idUser模型。

但是,相應的計算並未與登錄用戶相關聯。

我也試着計算手動連接到用戶:

class SessionsController < Devise::SessionsController 

    before_create :associate_calculation 

    def associate_calculation 
     Calculation.last.user_id = User.first.id 
     Calculation.last.save! 
    end 

end 

這也不能工作。

回答

1
def associate_calculation 
    c = Calculation.find(self.calculation_id) 
    c.user_id = self.id #self.id is probably also wrong. maybe current_user? 
    #Calculation.save! You can not save a class. You need to save an instance 
    c.save 
end 

保存對象不是類。你應該有一個錯誤,所以也要確保該方法實際上是通過添加一個跟蹤到你的日誌文件並檢查輸出來調用。

我也懷疑self.id可能不是你要找的。也許你應該尋找current_user.id?或者當前登錄的用戶對象的名稱。此外,如果你喜歡用模型關係則可能像

c.user = current_user 
c.save 

上述所有假設你有正確的協會如用戶has_many計算和計算belongs_to用戶,您的數據庫反映了這一點。我這樣說是因爲你提到:

我還將attr_accessor:calculation_id添加到用戶模型。

這顯然是錯誤的,永遠不會給你想要的結果,所以它看起來就像你有一點點混亂

只是添加到您的模型的方法不會有任何影響的。即使它確實起作用,您的解決方案也只允許爲用戶進行一次計算,但您的代碼意味着您將進行許多計算。 這導致我認爲你不應該只是找到一個計算,但應該創建一個?

您是否正確設置了路線?對於擴展控制器生效,您將需要somethign像

class SessionsController < Devise::SessionsController 
    def destroy 
    reset_session 
    super 
    end 
end 

# In your routes 

devise_for :users do 
    get "https://stackoverflow.com/users/sign_out", :to => "sessions#destroy", :as => "destroy_user_session" 
end 
+0

這個問題似乎蜂報'associate_calculation'不會被調用擺在首位。 – jonhue

+0

@jonhue這將解釋爲什麼你沒有看到你的代碼中的錯誤。所以當你得到這個排序,不同的問題?然後使用上面你應該得到你想要的結果 – jamesc

+0

@jonhue我已經更新了我的答案相當大。希望它能幫助你找到你真正需要的解決方案 – jamesc