0

I have a serialized field in my model

class Screen < ActiveRecord::Base
  serialize :options
end

The user should be able to add / edit n number of options for each record. I saw this SO question and tried

<%= f.fields_for :options do |o| %>
  <%= o.label :axis_y %>
  <%= o.text_field :axis_y %>
  <%= o.label :axis_x %>
  <%= o.text_field :axis_x %>
<% end %>

but my problem is I don't know what are the fields user want to add, and user can specify variable number of attributes foroptions. What is the best/proper way to to do this ? Any help much appreciated. Thanks

Community
  • 1
  • 1
Tony Vincent
  • 13,354
  • 7
  • 49
  • 68

1 Answers1

0

I've never seen serialize before, so I looked it up. Here's a tutorial; apparently you need to specify the type of the serialized object as well:

serialize :options, Hash

To whitelist the hash attrributes, you have a couple options.

You could create a custom validator (see here for instructions)

You can also overwrite the options= method:

def options=(val)
  whitelisted_keys = ["some", "keys"]
  if val.is_a?(Hash) && val.keys.all? { |key| whitelisted_keys.include? key }
    super
  else
    errors.add(:options, "is invalid")
    self
  end
end

You also might need to configure your screen_params method, so if things aren't working show that code in your question.

max pleaner
  • 26,189
  • 9
  • 66
  • 118