Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 799
Andrew Grimm Avatar asked Aug 25 '15 01:08

Andrew Grimm


1 Answers

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)

like image 133
joshua.paling Avatar answered Nov 16 '22 05:11

joshua.paling