2018年4月26日 星期四

Rails 不常用但可以變得很實用的 callback



## after_initialize && after_find

```ruby

class User < ApplicationRecord
  after_initialize do |user|
    puts "You have initialized an object!"
  end

  after_find do |user|
    puts "You have found an object!"
  end
end

>> User.new
You have initialized an object!
=> #<User id: nil>

>> User.first
You have found an object!
You have initialized an object!
=> #<User id: 1>
```

主要是 after_initialize 的部分,用來設定初始值挺方便的

http://guides.rubyonrails.org/active_record_callbacks.html#after-initialize-and-after-find


沒有留言:

張貼留言