Shpigford
Shpigford

Reputation: 25348

Edit a serialized hash in a form?

I'm serializing a hash that is stored in a settings field in a table, and would like to be able to edit that hash in a form field.

class Template < ActiveRecord::Base
  serialize :settings
end

But I just do <%= f.text_area :settings %> then the text area just shows the serialized data instead of the hash.

How can I get the hash to show in the text area?

Upvotes: 3

Views: 3512

Answers (3)

Wizard of Ogz
Wizard of Ogz

Reputation: 12643

Maybe setting up another accessor for your model would work.

class Template < ActiveRecord::Base
  serialize :settings
  attr_accessor :settings_edit

  before_save :handle_settings_edit, :if => lambda {|template| template.settings_edit.present? }

  def settings_edit
    read_attribute(:settings).inspect   # should display your hash like you want
  end

  protected
    def handle_settings_edit
      # You may want to perform eval in your validations instead of in a 
      # before_save callback, so that you can show errors on your form.
      begin
        self.settings = eval(settings_edit)
      rescue SyntaxError => e
        self.settings = settings_edit
      end
    end  
end

Then in your form use <%= f.text_area :settings_edit %>.

I have not tested any of this code, but in theory it should work. Good luck!

WARNING: Using eval like this is very dangerous, in this example a user could delete the entire Template table with one line in the edit box Template.destroy_all. Use a different method to convert the string to a hash if user input is involved.

Upvotes: 4

Anton Rogov
Anton Rogov

Reputation: 189

... or you could use something like this (without any logic in model):

<% @template.settings.each do |name, value| %>
  <div>
    <%= label_tag name %>
    <%= text_field_tag "template[settings][#{name}]", value %>
  </div>
<% end %>

Upvotes: 2

MKumar
MKumar

Reputation: 1524

you should use something like

class Template < ActiveRecord::Base
  serialize :settings, Hash
end

Upvotes: -2

Related Questions