Andrew Grimm
Andrew Grimm

Reputation: 81500

Changing enum value in Rails without saving model

How do I change an enum value without saving the model to the database yet?

The documentation for ActiveRecord::Enum indicates that methods like conversation.active! and conversation.status = "archived" is equivalent to doing conversation.update! status: 1, whereas I'm getting attributes from a simple_form form, and I don't want to save the model until all of the attributes have been set, as otherwise the model won't be valid.

Upvotes: 6

Views: 5485

Answers (1)

joshua.paling
joshua.paling

Reputation: 13952

The bang version of the method - conversation.active! will save to the database immediately.

The other way - conversation.status = "archived" will not, and will require an explicit conversation.save! afterwards. So, that's the method you're after.

(BTW, the rails console is really handy for testing stuff like this, and will even show you the exact sql that gets executed with the bang version of the method, as you execute it)

Upvotes: 8

Related Questions