Last Updated: February 25, 2016
· sdball

Use interactive_editor to update Rails models

The gem interactive_editor is great. It allows you to use your favorite editor within irb (or pry or ripl) to write ruby code and to introspect objects in YAML.

>> a = %w(a b c)
>> a.vim

[in editor]
- a
- b
- c

You can actually edit that YAML and it will be converted back into an object and returned to irb when you close your editor. That means that for normal objects, you can just assign the result wherever you like.

>> a = a.vim
# changes to the YAML will be saved back into a

But Rails objects don't work that way.

>> user = User.find(123)
#<User id: 1, email: \"user123@example.com\">"
>> user = user.vim
# edit the YAML, lets say you change the email field
>> user.inspect # email will *look* changed
"#<User id: 1, email: \"new.email@example.com\">"
>> user.changed?
>> user.save
true # but nothing happened

The problem is that we've sidestepped the usual Rails methods to update the object. That means that Rails doesn't know the object has changed and it's protecting us from needless writes to the database.

The data is there though, we just need to tell Rails about it. Of course, being Rails, it's a simple fix.

>> user.email_will_change!
>> user.changed?
>> user.save
true # done!
Say Thanks