rails 5.2 model attributes assignment 要注意的地方

當透過 association build model 時,要注意 value assignment 的順序

MarsZ 黃金俠閱讀 1 分鐘
rails 5.2 model attributes assignment 要注意的地方
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 才行。

關於作者MarsZ 黃金俠自由接案工程師 | Ruby on Rails

自由接案者、Ruby on Rails 工程師、水肺潛水員、業餘羽球、二胡、鋼琴愛好者。喜歡貓、狗。

延伸閱讀

加入 BNI 商會心得

於 2023/10 加入了 BNI 台南商會(大信白金),本篇文章將分享加入後的心得,並持續更新心得內容,確認在不同階段的自己是否有偏離初衷。

閱讀 3 分鐘