How to edit a Rails serialized field in a form?

后端 未结 8 693
-上瘾入骨i
-上瘾入骨i 2020-12-04 07:16

I have a data model in my Rails project that has a serialized field:

class Widget < ActiveRecord::Base
  serialize :options
end

The opti

8条回答
  •  抹茶落季
    2020-12-04 08:07

    emh is almost there. I would think that Rails would return the values to the form fields but it does not. So you can just put it in there manually in the ":value =>" parameter for each field. It doesn't look slick, but it works.

    Here it is from top to bottom:

    class Widget < ActiveRecord::Base
        serialize :options, Hash
    end
    
    <%= form_for :widget, @widget, :url => {:action => "update"}, :html => {:method => :put} do |f| %>
    <%= f.error_messages %>
        <%= f.fields_for :options do |o| %>
            <%= o.text_field :axis_x, :size => 10, :value => @widget.options["axis_x"] %>
            <%= o.text_field :axis_y, :size => 10, :value => @widget.options["axis_y"] %>
        <% end %>
    <% end %>
    

    Any field you add in the "fields_for" will show up in the serialized hash. You can add or remove fields at will. They will be passed as attributes to the "options" hash and stored as YAML.

提交回复
热议问题