2014-08-31 39 views
0

爲什麼這不是保存值?模型回調是通過一個錯誤(after_create)

每次創建新用戶時,都應該設置默認設置並在設置模型中創建一個條目。 如果我手動創建,用戶/設置關聯可以很好地工作。通過PSQL軌道ç

class User < ActiveRecord::Base 
     after_create do 
     if self.setting.nil? # check if user got settings most likely not 
      # call settings model and create new default settings 
      Setting.create(:user_id => self.id, :foo => "bar", :baz => true) 
     end 
     end 
end 

是名稱是否正確,以及例如如果我創建了一個用戶設置和我想查詢的用戶設置我必須使用:

current_user.setting.language 

這是愚蠢的,因爲它應該是複數,但它的作品,所以不要擔心任何命名約定或在我的回調簡單的拼寫錯誤。

事實上,它實際上不是一個錯誤,但值不會被保存。 這裏的過程是:

用戶創建一個新帳戶,這個回調應該建立在設置頁面上默認設置也需要像設置ID,這樣一個div:

<h2 data-settings_id="<%= current_user.setting.id %>" id="current_user" data-user="<%= current_user.id %>">Settings </h2> 

如果我手動創建的設置此頁正常工作 - 所以我想,既然我得到這個錯誤的回調也沒有創造任何設置:

undefined method `id' for nil:NilClass 

注: 我使用的設計,我不希望覆蓋任何類。 如何解決這個問題?感謝

+0

'所以我想..'也許你可以只檢查呢? – IS04 2014-08-31 12:29:28

+0

檢查什麼?我沒有創建任何值... – 2014-08-31 12:31:31

回答

0

我認爲這個問題是在回調的條件:

self.setting.nil? 

由於setting是一種關係,它應該返回一個的ActiveRecord ::協會:: CollectionProxy對象,它更象是一個Array與檢查nil?將始終返回false,您需要使用blank?進行檢查。

這樣的事情,應該工作:

class User < ActiveRecord::Base 
    after_create do 
    if self.setting.blank? # check if user got settings most likely not 
     # call settings model and create new default settings 
     self.setting.create(:foo => "bar", :baz => true) # user_id will be set for us since we initiated the new object using the relation 
    end 
    end 
end 
+0

謝謝你的時間。現在它可以工作。 – 2014-08-31 12:34:34

相關問題