Isaac Sloan - Saving dynamic serialized fields with fields_for in Rails
Banner700

Saving dynamic serialized fields with fields_for in Rails

Tell you model to serialize it as a struct and create a setter to build the struct on create.

# post.rb model
serialize :content, OpenStruct
def content=(v)
  self[:content] = OpenStruct.new(v)
end

Then you can add any form elements you want for content.

-#form partial

= f.fields_for :content, @post.content do |ff|
  .field
    = ff.label :name
    = ff.text_field :name
  .field
    = ff.label :age
    = ff.number_field :age

Make sure to all your field through strong_params.

February 23, 2015
rubyrails
comments powered by Disqus