ruby - serialize & before_save in Rails 4 -


i have documenttype model w/ extensions attribute. in form i'm allowing people insert extensions form.

i want able parse input before saving, stripping out invalid options, convert array , have rails serialize it.

i have following code end w/ input user gave in form instead of array:

class documenttype < activerecord::base   serialize :extensions    before_save :process_extensions    def process_extensions     self.extensions = [*self.extensions.gsub(/[^a-z ]+/i, '').split(' ')].uniq   end end 

the key understanding what's happening knowing when serialization occurs. inspecting serialization.rb in activerecord you'll see serialization magic happens overriding type_cast_attribute_for_write, called on write_attribute. is, on attribute assignment. when do:

document_type.extensions = 

something gets serialized , written extensions attribute. way before save takes place. in fact, don't have call save on document_type have attribute serialized.

the best workaround know override extensions= on documenttype. like:

def extensions=(value)   value = [*value.gsub(/[^a-z ]+/i, '').split(' ')].uniq   write_attribute :extensions, value end 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -