user.profiles.new(mobile: '0988123456')

我們知道上面這段 code 得到的 profile model,裡面的 value 會有 user_id 和 mobile

不過 assignment 的順序是 mobile -> user_id

所以當你 overwrite setter method 時,例如

def mobile=(value)
  user.country_code + value.to_s
end

這時 user 肯定是 null

所以得把這樣的處理移到 before_save 或先 new 出來後再 assign_attributes 才行。