ruby on rails添加了模型属性更改的功能

Dan*_*iel 2 ruby metaprogramming ruby-on-rails alias-method

在我的rails模型中,我有一个名为employer_wcb的小数属性.如果在更改employer_wcb时将脏位设置为true,我希望如此.我想覆盖employer_wcb setter方法.有没有办法(特别是使用元编程)?

And*_*ack 8

实际上,从Rails v2.1开始,这已经融入了Rails.看看ActiveRecord :: Dirty文档.综上所述:

# Create a new Thing model instance;
# Dirty bit should be unset...
t = Thing.new
t.changed?              # => false
t.employer_wcb_changed? # => false

# Now set the attribute and note the dirty bits.
t.employer_wcb = 0.525
t.changed?              # => true
t.employer_wcb_changed? # => true
t.id_changed?           # => false

# The dirty bit goes away when you save changes.
t.save
t.changed?              # => false
t.employer_wcb_changed? # => false
Run Code Online (Sandbox Code Playgroud)