How to edit a Rails serialized field in a form?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







55















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



class Widget < ActiveRecord::Base
serialize :options
end


The options field can have variable data info. For example, here is the options field for one record from the fixtures file:



  options:
query_id: 2
axis_y: 'percent'
axis_x: 'text'
units: '%'
css_class: 'occupancy'
dom_hook: '#average-occupancy-by-day'
table_scale: 1


My question is what is the proper way to let a user edit this info in a standard form view?



If you just use a simple text area field for the options field, you would just get a yaml dump representation and that data would just be sent back as a string.



What is the best/proper way to edit a serialized hash field like this in Rails?










share|improve this question























  • What kind of interface would you like? Should there be fields for each attribute? Do you know what all of the attributes are up front?

    – BJ Clark
    Jun 17 '09 at 4:00











  • All the attributes won't be known up front. Some are standard and will always be present but the rest can be user defined. This is an admin-only interface so I trust the user input to a much larger extent than normal. I actually just used a textarea box and let the user input the key:value pairs using YAML markup and it worked fine all the way through

    – cpjolicoeur
    Jun 17 '09 at 13:30


















55















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



class Widget < ActiveRecord::Base
serialize :options
end


The options field can have variable data info. For example, here is the options field for one record from the fixtures file:



  options:
query_id: 2
axis_y: 'percent'
axis_x: 'text'
units: '%'
css_class: 'occupancy'
dom_hook: '#average-occupancy-by-day'
table_scale: 1


My question is what is the proper way to let a user edit this info in a standard form view?



If you just use a simple text area field for the options field, you would just get a yaml dump representation and that data would just be sent back as a string.



What is the best/proper way to edit a serialized hash field like this in Rails?










share|improve this question























  • What kind of interface would you like? Should there be fields for each attribute? Do you know what all of the attributes are up front?

    – BJ Clark
    Jun 17 '09 at 4:00











  • All the attributes won't be known up front. Some are standard and will always be present but the rest can be user defined. This is an admin-only interface so I trust the user input to a much larger extent than normal. I actually just used a textarea box and let the user input the key:value pairs using YAML markup and it worked fine all the way through

    – cpjolicoeur
    Jun 17 '09 at 13:30














55












55








55


32






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



class Widget < ActiveRecord::Base
serialize :options
end


The options field can have variable data info. For example, here is the options field for one record from the fixtures file:



  options:
query_id: 2
axis_y: 'percent'
axis_x: 'text'
units: '%'
css_class: 'occupancy'
dom_hook: '#average-occupancy-by-day'
table_scale: 1


My question is what is the proper way to let a user edit this info in a standard form view?



If you just use a simple text area field for the options field, you would just get a yaml dump representation and that data would just be sent back as a string.



What is the best/proper way to edit a serialized hash field like this in Rails?










share|improve this question














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



class Widget < ActiveRecord::Base
serialize :options
end


The options field can have variable data info. For example, here is the options field for one record from the fixtures file:



  options:
query_id: 2
axis_y: 'percent'
axis_x: 'text'
units: '%'
css_class: 'occupancy'
dom_hook: '#average-occupancy-by-day'
table_scale: 1


My question is what is the proper way to let a user edit this info in a standard form view?



If you just use a simple text area field for the options field, you would just get a yaml dump representation and that data would just be sent back as a string.



What is the best/proper way to edit a serialized hash field like this in Rails?







ruby-on-rails forms serialization






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jun 16 '09 at 17:48









cpjolicoeurcpjolicoeur

9,59964055




9,59964055













  • What kind of interface would you like? Should there be fields for each attribute? Do you know what all of the attributes are up front?

    – BJ Clark
    Jun 17 '09 at 4:00











  • All the attributes won't be known up front. Some are standard and will always be present but the rest can be user defined. This is an admin-only interface so I trust the user input to a much larger extent than normal. I actually just used a textarea box and let the user input the key:value pairs using YAML markup and it worked fine all the way through

    – cpjolicoeur
    Jun 17 '09 at 13:30



















  • What kind of interface would you like? Should there be fields for each attribute? Do you know what all of the attributes are up front?

    – BJ Clark
    Jun 17 '09 at 4:00











  • All the attributes won't be known up front. Some are standard and will always be present but the rest can be user defined. This is an admin-only interface so I trust the user input to a much larger extent than normal. I actually just used a textarea box and let the user input the key:value pairs using YAML markup and it worked fine all the way through

    – cpjolicoeur
    Jun 17 '09 at 13:30

















What kind of interface would you like? Should there be fields for each attribute? Do you know what all of the attributes are up front?

– BJ Clark
Jun 17 '09 at 4:00





What kind of interface would you like? Should there be fields for each attribute? Do you know what all of the attributes are up front?

– BJ Clark
Jun 17 '09 at 4:00













All the attributes won't be known up front. Some are standard and will always be present but the rest can be user defined. This is an admin-only interface so I trust the user input to a much larger extent than normal. I actually just used a textarea box and let the user input the key:value pairs using YAML markup and it worked fine all the way through

– cpjolicoeur
Jun 17 '09 at 13:30





All the attributes won't be known up front. Some are standard and will always be present but the rest can be user defined. This is an admin-only interface so I trust the user input to a much larger extent than normal. I actually just used a textarea box and let the user input the key:value pairs using YAML markup and it worked fine all the way through

– cpjolicoeur
Jun 17 '09 at 13:30












8 Answers
8






active

oldest

votes


















57














If you know what the option keys are going to be in advance, you can declare special getters and setters for them like so:



class Widget < ActiveRecord::Base
serialize :options

def self.serialized_attr_accessor(*args)
args.each do |method_name|
eval "
def #{method_name}
(self.options || {})[:#{method_name}]
end
def #{method_name}=(value)
self.options ||= {}
self.options[:#{method_name}] = value
end
attr_accessible :#{method_name}
"
end
end

serialized_attr_accessor :query_id, :axis_y, :axis_x, :units
end


The nice thing about this is that it exposes the components of the options array as attributes, which allows you to use the Rails form helpers like so:



#haml
- form_for @widget do |f|
= f.text_field :axis_y
= f.text_field :axis_x
= f.text_field :unit





share|improve this answer


























  • Thanks, but I dont know all the option values ahead of time. Some of them will always be present, but the rest can be user defined.

    – cpjolicoeur
    Jun 17 '09 at 13:30











  • Yep, that would be great to create those accessors dynamically

    – Artur79
    Jul 25 '12 at 11:47






  • 1





    its good to add at the end of the eval: attr_accessible method_name

    – Artur79
    Feb 1 '13 at 14:31













  • @Artur79: good idea, done

    – austinfromboston
    Feb 1 '13 at 20:37











  • Is the solution also updates the hash value in saving? even not all keys are in form? Will it not remove the existing in records?

    – aldrien.h
    Feb 28 '18 at 10:19



















38














Well, I had the same problem, and tried not to over-engineer it. The problem is, that although you can pass the serialized hash to fields_for, the fields for function will think, it is an option hash (and not your object), and set the form object to nil. This means, that although you can edit the values, they will not appear after editing. It might be a bug or unexpected behavior of rails and maybe fixed in the future.



However, for now, it is quite easy to get it working (though it took me the whole morning to figure out).



You can leave you model as is and in the view you need to give fields for the object as an open struct. That will properly set the record object (so f2.object will return your options) and secondly it lets the text_field builder access the value from your object/params.



Since I included " || {}", it will work with new/create forms, too.



= form_for @widget do |f|
= f.fields_for :options, OpenStruct.new(f.object.options || {}) do |f2|
= f2.text_field :axis_y
= f2.text_field :axis_x
= f2.text_field :unit


Have a great day






share|improve this answer





















  • 1





    Well done. This tip saved me some time tonight. I didn't think about the fact that the object was a hash would mean it would get interpreted as an options hash, but if that's indeed what's going on, it makes a lot of sense.

    – Legion
    Jun 1 '12 at 1:59






  • 1





    I really really like this solution, I've added this to my model to complete it: def options OpenStruct.new self[:options] || {} end, so you get the OpenStruct always when reading the attribute..

    – Tim Baas
    Mar 13 '13 at 15:32








  • 2





    I think there is a little mistake: you should call text_field on f2, not f

    – Sidhannowe
    Nov 22 '13 at 10:51











  • Thanks for hint Sidhannowe, I fixed it ^_^

    – Christian Butzke
    Dec 10 '13 at 14:51











  • Well done, love the solution.

    – Haris Krajina
    Feb 7 '17 at 16:18



















29














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.






share|improve this answer
























  • I am trying to do as you said, but it does not seem to work for me: stackoverflow.com/questions/6621341

    – Nicolas Raoul
    Jul 8 '11 at 8:16





















4














I've been struggling with a very similar problem. The solutions I found here were very helpful to me. Thank you @austinfromboston, @Christian-Butske, @sbzoom, and everyone else. However, I think these answers might be slightly out-of-date. Here's what worked for me with Rails 5 and ruby 2.3:



In the form:



<%= f.label :options %>
<%= 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 %>


and then in the controller I had to update the strong parameters like so:



def widget_params
params.require(:widget).permit(:any, :regular, :parameters, :options => [:axis_y, :axis_x, ...])
end


It seems to be important that the serialized hash parameter comes at the end of the list of parameters. Otherwise, Rails will expect the next parameter to also be a serialized hash.



In the view I used some simple if/then logic to only display the hash if it is not empty and then to only display key/value pairs where the value was not nil.






share|improve this answer
























  • This works for storing values, but when you open the edit form, you do not see the values you saved

    – Yaro Shm
    Feb 26 '18 at 19:58











  • @YaroShm It's been a while since I visited this problem. As I remember the strong parameters were a little bit tricky and updates to rails over the past year may have changed the necessary syntax. It'll probably take some careful debugging and maybe a little lucky poking to get it working. When you do, please post the trick here. It will help other developers that find this post in the future. Best of luck!

    – JDenman6
    Mar 2 '18 at 1:32



















3














No need setter/getters, I just defined in the model:



serialize :content_hash, Hash


Then in the view, I do (with simple_form, but similar with vanilla Rails):



  = f.simple_fields_for :content_hash do |chf|
- @model_instance.content_hash.each_pair do |k,v|
=chf.input k.to_sym, :as => :string, :input_html => {:value => v}


My last issue is how to let the user add a new key/value pair.






share|improve this answer
























  • Mostly worked, except I'm dealing with a deep hash and only the root level ends up as a hash with this.

    – cpuguy83
    Aug 22 '12 at 13:33



















2














I will suggest something simple, because all the time, when user will save form You will get string. So You can use for example before filter and parse those data like that:



before_save do
widget.options = YAML.parse(widget.options).to_ruby
end


of course You should add validation if this is correct YAML.
But it should works.






share|improve this answer































    1














    I'm trying to do something similar and I found this sort of works:



    <%= form_for @search do |f| %>
    <%= f.fields_for :params, @search.params do |p| %>
    <%= p.select "property_id", [[ "All", 0 ]] + PropertyType.all.collect { |pt| [ pt.value, pt.id ] } %>

    <%= p.text_field :min_square_footage, :size => 10, :placeholder => "Min" %>
    <%= p.text_field :max_square_footage, :size => 10, :placeholder => "Max" %>
    <% end %>
    <% end %>


    except that the form fields aren't populated when the form is rendered. when the form is submitted the values come through just fine and i can do:



    @search = Search.new(params[:search])


    so its "half" working...






    share|improve this answer































      1














      I was facing the same issue, after some research i found a solution using Rails' store_accessor to make keys of a serialized column accessible as attributes.



      With this we can access "nested" attributes of a serialized column …



      # post.rb
      class Post < ApplicationRecord
      serialize :options
      store_accessor :options, :value1, :value2, :value3
      end

      # set / get values
      post = Post.new
      post.value1 = "foo"
      post.value1
      #=> "foo"
      post.options['value1']
      #=> "foo"

      # strong parameters in posts_controller.rb
      params.require(:post).permit(:value1, :value2, :value3)

      # form.html.erb
      <%= form_with model: @post, local: true do |f| %>
      <%= f.label :value1 %>
      <%= f.text_field :value1 %>
      # …
      <% end %>





      share|improve this answer
























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1002963%2fhow-to-edit-a-rails-serialized-field-in-a-form%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        8 Answers
        8






        active

        oldest

        votes








        8 Answers
        8






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        57














        If you know what the option keys are going to be in advance, you can declare special getters and setters for them like so:



        class Widget < ActiveRecord::Base
        serialize :options

        def self.serialized_attr_accessor(*args)
        args.each do |method_name|
        eval "
        def #{method_name}
        (self.options || {})[:#{method_name}]
        end
        def #{method_name}=(value)
        self.options ||= {}
        self.options[:#{method_name}] = value
        end
        attr_accessible :#{method_name}
        "
        end
        end

        serialized_attr_accessor :query_id, :axis_y, :axis_x, :units
        end


        The nice thing about this is that it exposes the components of the options array as attributes, which allows you to use the Rails form helpers like so:



        #haml
        - form_for @widget do |f|
        = f.text_field :axis_y
        = f.text_field :axis_x
        = f.text_field :unit





        share|improve this answer


























        • Thanks, but I dont know all the option values ahead of time. Some of them will always be present, but the rest can be user defined.

          – cpjolicoeur
          Jun 17 '09 at 13:30











        • Yep, that would be great to create those accessors dynamically

          – Artur79
          Jul 25 '12 at 11:47






        • 1





          its good to add at the end of the eval: attr_accessible method_name

          – Artur79
          Feb 1 '13 at 14:31













        • @Artur79: good idea, done

          – austinfromboston
          Feb 1 '13 at 20:37











        • Is the solution also updates the hash value in saving? even not all keys are in form? Will it not remove the existing in records?

          – aldrien.h
          Feb 28 '18 at 10:19
















        57














        If you know what the option keys are going to be in advance, you can declare special getters and setters for them like so:



        class Widget < ActiveRecord::Base
        serialize :options

        def self.serialized_attr_accessor(*args)
        args.each do |method_name|
        eval "
        def #{method_name}
        (self.options || {})[:#{method_name}]
        end
        def #{method_name}=(value)
        self.options ||= {}
        self.options[:#{method_name}] = value
        end
        attr_accessible :#{method_name}
        "
        end
        end

        serialized_attr_accessor :query_id, :axis_y, :axis_x, :units
        end


        The nice thing about this is that it exposes the components of the options array as attributes, which allows you to use the Rails form helpers like so:



        #haml
        - form_for @widget do |f|
        = f.text_field :axis_y
        = f.text_field :axis_x
        = f.text_field :unit





        share|improve this answer


























        • Thanks, but I dont know all the option values ahead of time. Some of them will always be present, but the rest can be user defined.

          – cpjolicoeur
          Jun 17 '09 at 13:30











        • Yep, that would be great to create those accessors dynamically

          – Artur79
          Jul 25 '12 at 11:47






        • 1





          its good to add at the end of the eval: attr_accessible method_name

          – Artur79
          Feb 1 '13 at 14:31













        • @Artur79: good idea, done

          – austinfromboston
          Feb 1 '13 at 20:37











        • Is the solution also updates the hash value in saving? even not all keys are in form? Will it not remove the existing in records?

          – aldrien.h
          Feb 28 '18 at 10:19














        57












        57








        57







        If you know what the option keys are going to be in advance, you can declare special getters and setters for them like so:



        class Widget < ActiveRecord::Base
        serialize :options

        def self.serialized_attr_accessor(*args)
        args.each do |method_name|
        eval "
        def #{method_name}
        (self.options || {})[:#{method_name}]
        end
        def #{method_name}=(value)
        self.options ||= {}
        self.options[:#{method_name}] = value
        end
        attr_accessible :#{method_name}
        "
        end
        end

        serialized_attr_accessor :query_id, :axis_y, :axis_x, :units
        end


        The nice thing about this is that it exposes the components of the options array as attributes, which allows you to use the Rails form helpers like so:



        #haml
        - form_for @widget do |f|
        = f.text_field :axis_y
        = f.text_field :axis_x
        = f.text_field :unit





        share|improve this answer















        If you know what the option keys are going to be in advance, you can declare special getters and setters for them like so:



        class Widget < ActiveRecord::Base
        serialize :options

        def self.serialized_attr_accessor(*args)
        args.each do |method_name|
        eval "
        def #{method_name}
        (self.options || {})[:#{method_name}]
        end
        def #{method_name}=(value)
        self.options ||= {}
        self.options[:#{method_name}] = value
        end
        attr_accessible :#{method_name}
        "
        end
        end

        serialized_attr_accessor :query_id, :axis_y, :axis_x, :units
        end


        The nice thing about this is that it exposes the components of the options array as attributes, which allows you to use the Rails form helpers like so:



        #haml
        - form_for @widget do |f|
        = f.text_field :axis_y
        = f.text_field :axis_x
        = f.text_field :unit






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Feb 1 '13 at 20:37

























        answered Jun 16 '09 at 21:17









        austinfrombostonaustinfromboston

        3,6111825




        3,6111825













        • Thanks, but I dont know all the option values ahead of time. Some of them will always be present, but the rest can be user defined.

          – cpjolicoeur
          Jun 17 '09 at 13:30











        • Yep, that would be great to create those accessors dynamically

          – Artur79
          Jul 25 '12 at 11:47






        • 1





          its good to add at the end of the eval: attr_accessible method_name

          – Artur79
          Feb 1 '13 at 14:31













        • @Artur79: good idea, done

          – austinfromboston
          Feb 1 '13 at 20:37











        • Is the solution also updates the hash value in saving? even not all keys are in form? Will it not remove the existing in records?

          – aldrien.h
          Feb 28 '18 at 10:19



















        • Thanks, but I dont know all the option values ahead of time. Some of them will always be present, but the rest can be user defined.

          – cpjolicoeur
          Jun 17 '09 at 13:30











        • Yep, that would be great to create those accessors dynamically

          – Artur79
          Jul 25 '12 at 11:47






        • 1





          its good to add at the end of the eval: attr_accessible method_name

          – Artur79
          Feb 1 '13 at 14:31













        • @Artur79: good idea, done

          – austinfromboston
          Feb 1 '13 at 20:37











        • Is the solution also updates the hash value in saving? even not all keys are in form? Will it not remove the existing in records?

          – aldrien.h
          Feb 28 '18 at 10:19

















        Thanks, but I dont know all the option values ahead of time. Some of them will always be present, but the rest can be user defined.

        – cpjolicoeur
        Jun 17 '09 at 13:30





        Thanks, but I dont know all the option values ahead of time. Some of them will always be present, but the rest can be user defined.

        – cpjolicoeur
        Jun 17 '09 at 13:30













        Yep, that would be great to create those accessors dynamically

        – Artur79
        Jul 25 '12 at 11:47





        Yep, that would be great to create those accessors dynamically

        – Artur79
        Jul 25 '12 at 11:47




        1




        1





        its good to add at the end of the eval: attr_accessible method_name

        – Artur79
        Feb 1 '13 at 14:31







        its good to add at the end of the eval: attr_accessible method_name

        – Artur79
        Feb 1 '13 at 14:31















        @Artur79: good idea, done

        – austinfromboston
        Feb 1 '13 at 20:37





        @Artur79: good idea, done

        – austinfromboston
        Feb 1 '13 at 20:37













        Is the solution also updates the hash value in saving? even not all keys are in form? Will it not remove the existing in records?

        – aldrien.h
        Feb 28 '18 at 10:19





        Is the solution also updates the hash value in saving? even not all keys are in form? Will it not remove the existing in records?

        – aldrien.h
        Feb 28 '18 at 10:19













        38














        Well, I had the same problem, and tried not to over-engineer it. The problem is, that although you can pass the serialized hash to fields_for, the fields for function will think, it is an option hash (and not your object), and set the form object to nil. This means, that although you can edit the values, they will not appear after editing. It might be a bug or unexpected behavior of rails and maybe fixed in the future.



        However, for now, it is quite easy to get it working (though it took me the whole morning to figure out).



        You can leave you model as is and in the view you need to give fields for the object as an open struct. That will properly set the record object (so f2.object will return your options) and secondly it lets the text_field builder access the value from your object/params.



        Since I included " || {}", it will work with new/create forms, too.



        = form_for @widget do |f|
        = f.fields_for :options, OpenStruct.new(f.object.options || {}) do |f2|
        = f2.text_field :axis_y
        = f2.text_field :axis_x
        = f2.text_field :unit


        Have a great day






        share|improve this answer





















        • 1





          Well done. This tip saved me some time tonight. I didn't think about the fact that the object was a hash would mean it would get interpreted as an options hash, but if that's indeed what's going on, it makes a lot of sense.

          – Legion
          Jun 1 '12 at 1:59






        • 1





          I really really like this solution, I've added this to my model to complete it: def options OpenStruct.new self[:options] || {} end, so you get the OpenStruct always when reading the attribute..

          – Tim Baas
          Mar 13 '13 at 15:32








        • 2





          I think there is a little mistake: you should call text_field on f2, not f

          – Sidhannowe
          Nov 22 '13 at 10:51











        • Thanks for hint Sidhannowe, I fixed it ^_^

          – Christian Butzke
          Dec 10 '13 at 14:51











        • Well done, love the solution.

          – Haris Krajina
          Feb 7 '17 at 16:18
















        38














        Well, I had the same problem, and tried not to over-engineer it. The problem is, that although you can pass the serialized hash to fields_for, the fields for function will think, it is an option hash (and not your object), and set the form object to nil. This means, that although you can edit the values, they will not appear after editing. It might be a bug or unexpected behavior of rails and maybe fixed in the future.



        However, for now, it is quite easy to get it working (though it took me the whole morning to figure out).



        You can leave you model as is and in the view you need to give fields for the object as an open struct. That will properly set the record object (so f2.object will return your options) and secondly it lets the text_field builder access the value from your object/params.



        Since I included " || {}", it will work with new/create forms, too.



        = form_for @widget do |f|
        = f.fields_for :options, OpenStruct.new(f.object.options || {}) do |f2|
        = f2.text_field :axis_y
        = f2.text_field :axis_x
        = f2.text_field :unit


        Have a great day






        share|improve this answer





















        • 1





          Well done. This tip saved me some time tonight. I didn't think about the fact that the object was a hash would mean it would get interpreted as an options hash, but if that's indeed what's going on, it makes a lot of sense.

          – Legion
          Jun 1 '12 at 1:59






        • 1





          I really really like this solution, I've added this to my model to complete it: def options OpenStruct.new self[:options] || {} end, so you get the OpenStruct always when reading the attribute..

          – Tim Baas
          Mar 13 '13 at 15:32








        • 2





          I think there is a little mistake: you should call text_field on f2, not f

          – Sidhannowe
          Nov 22 '13 at 10:51











        • Thanks for hint Sidhannowe, I fixed it ^_^

          – Christian Butzke
          Dec 10 '13 at 14:51











        • Well done, love the solution.

          – Haris Krajina
          Feb 7 '17 at 16:18














        38












        38








        38







        Well, I had the same problem, and tried not to over-engineer it. The problem is, that although you can pass the serialized hash to fields_for, the fields for function will think, it is an option hash (and not your object), and set the form object to nil. This means, that although you can edit the values, they will not appear after editing. It might be a bug or unexpected behavior of rails and maybe fixed in the future.



        However, for now, it is quite easy to get it working (though it took me the whole morning to figure out).



        You can leave you model as is and in the view you need to give fields for the object as an open struct. That will properly set the record object (so f2.object will return your options) and secondly it lets the text_field builder access the value from your object/params.



        Since I included " || {}", it will work with new/create forms, too.



        = form_for @widget do |f|
        = f.fields_for :options, OpenStruct.new(f.object.options || {}) do |f2|
        = f2.text_field :axis_y
        = f2.text_field :axis_x
        = f2.text_field :unit


        Have a great day






        share|improve this answer















        Well, I had the same problem, and tried not to over-engineer it. The problem is, that although you can pass the serialized hash to fields_for, the fields for function will think, it is an option hash (and not your object), and set the form object to nil. This means, that although you can edit the values, they will not appear after editing. It might be a bug or unexpected behavior of rails and maybe fixed in the future.



        However, for now, it is quite easy to get it working (though it took me the whole morning to figure out).



        You can leave you model as is and in the view you need to give fields for the object as an open struct. That will properly set the record object (so f2.object will return your options) and secondly it lets the text_field builder access the value from your object/params.



        Since I included " || {}", it will work with new/create forms, too.



        = form_for @widget do |f|
        = f.fields_for :options, OpenStruct.new(f.object.options || {}) do |f2|
        = f2.text_field :axis_y
        = f2.text_field :axis_x
        = f2.text_field :unit


        Have a great day







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Dec 10 '13 at 14:50

























        answered May 21 '12 at 7:21









        Christian ButzkeChristian Butzke

        946106




        946106








        • 1





          Well done. This tip saved me some time tonight. I didn't think about the fact that the object was a hash would mean it would get interpreted as an options hash, but if that's indeed what's going on, it makes a lot of sense.

          – Legion
          Jun 1 '12 at 1:59






        • 1





          I really really like this solution, I've added this to my model to complete it: def options OpenStruct.new self[:options] || {} end, so you get the OpenStruct always when reading the attribute..

          – Tim Baas
          Mar 13 '13 at 15:32








        • 2





          I think there is a little mistake: you should call text_field on f2, not f

          – Sidhannowe
          Nov 22 '13 at 10:51











        • Thanks for hint Sidhannowe, I fixed it ^_^

          – Christian Butzke
          Dec 10 '13 at 14:51











        • Well done, love the solution.

          – Haris Krajina
          Feb 7 '17 at 16:18














        • 1





          Well done. This tip saved me some time tonight. I didn't think about the fact that the object was a hash would mean it would get interpreted as an options hash, but if that's indeed what's going on, it makes a lot of sense.

          – Legion
          Jun 1 '12 at 1:59






        • 1





          I really really like this solution, I've added this to my model to complete it: def options OpenStruct.new self[:options] || {} end, so you get the OpenStruct always when reading the attribute..

          – Tim Baas
          Mar 13 '13 at 15:32








        • 2





          I think there is a little mistake: you should call text_field on f2, not f

          – Sidhannowe
          Nov 22 '13 at 10:51











        • Thanks for hint Sidhannowe, I fixed it ^_^

          – Christian Butzke
          Dec 10 '13 at 14:51











        • Well done, love the solution.

          – Haris Krajina
          Feb 7 '17 at 16:18








        1




        1





        Well done. This tip saved me some time tonight. I didn't think about the fact that the object was a hash would mean it would get interpreted as an options hash, but if that's indeed what's going on, it makes a lot of sense.

        – Legion
        Jun 1 '12 at 1:59





        Well done. This tip saved me some time tonight. I didn't think about the fact that the object was a hash would mean it would get interpreted as an options hash, but if that's indeed what's going on, it makes a lot of sense.

        – Legion
        Jun 1 '12 at 1:59




        1




        1





        I really really like this solution, I've added this to my model to complete it: def options OpenStruct.new self[:options] || {} end, so you get the OpenStruct always when reading the attribute..

        – Tim Baas
        Mar 13 '13 at 15:32







        I really really like this solution, I've added this to my model to complete it: def options OpenStruct.new self[:options] || {} end, so you get the OpenStruct always when reading the attribute..

        – Tim Baas
        Mar 13 '13 at 15:32






        2




        2





        I think there is a little mistake: you should call text_field on f2, not f

        – Sidhannowe
        Nov 22 '13 at 10:51





        I think there is a little mistake: you should call text_field on f2, not f

        – Sidhannowe
        Nov 22 '13 at 10:51













        Thanks for hint Sidhannowe, I fixed it ^_^

        – Christian Butzke
        Dec 10 '13 at 14:51





        Thanks for hint Sidhannowe, I fixed it ^_^

        – Christian Butzke
        Dec 10 '13 at 14:51













        Well done, love the solution.

        – Haris Krajina
        Feb 7 '17 at 16:18





        Well done, love the solution.

        – Haris Krajina
        Feb 7 '17 at 16:18











        29














        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.






        share|improve this answer
























        • I am trying to do as you said, but it does not seem to work for me: stackoverflow.com/questions/6621341

          – Nicolas Raoul
          Jul 8 '11 at 8:16


















        29














        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.






        share|improve this answer
























        • I am trying to do as you said, but it does not seem to work for me: stackoverflow.com/questions/6621341

          – Nicolas Raoul
          Jul 8 '11 at 8:16
















        29












        29








        29







        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.






        share|improve this answer













        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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 26 '11 at 20:46









        sbzoomsbzoom

        2,34142028




        2,34142028













        • I am trying to do as you said, but it does not seem to work for me: stackoverflow.com/questions/6621341

          – Nicolas Raoul
          Jul 8 '11 at 8:16





















        • I am trying to do as you said, but it does not seem to work for me: stackoverflow.com/questions/6621341

          – Nicolas Raoul
          Jul 8 '11 at 8:16



















        I am trying to do as you said, but it does not seem to work for me: stackoverflow.com/questions/6621341

        – Nicolas Raoul
        Jul 8 '11 at 8:16







        I am trying to do as you said, but it does not seem to work for me: stackoverflow.com/questions/6621341

        – Nicolas Raoul
        Jul 8 '11 at 8:16













        4














        I've been struggling with a very similar problem. The solutions I found here were very helpful to me. Thank you @austinfromboston, @Christian-Butske, @sbzoom, and everyone else. However, I think these answers might be slightly out-of-date. Here's what worked for me with Rails 5 and ruby 2.3:



        In the form:



        <%= f.label :options %>
        <%= 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 %>


        and then in the controller I had to update the strong parameters like so:



        def widget_params
        params.require(:widget).permit(:any, :regular, :parameters, :options => [:axis_y, :axis_x, ...])
        end


        It seems to be important that the serialized hash parameter comes at the end of the list of parameters. Otherwise, Rails will expect the next parameter to also be a serialized hash.



        In the view I used some simple if/then logic to only display the hash if it is not empty and then to only display key/value pairs where the value was not nil.






        share|improve this answer
























        • This works for storing values, but when you open the edit form, you do not see the values you saved

          – Yaro Shm
          Feb 26 '18 at 19:58











        • @YaroShm It's been a while since I visited this problem. As I remember the strong parameters were a little bit tricky and updates to rails over the past year may have changed the necessary syntax. It'll probably take some careful debugging and maybe a little lucky poking to get it working. When you do, please post the trick here. It will help other developers that find this post in the future. Best of luck!

          – JDenman6
          Mar 2 '18 at 1:32
















        4














        I've been struggling with a very similar problem. The solutions I found here were very helpful to me. Thank you @austinfromboston, @Christian-Butske, @sbzoom, and everyone else. However, I think these answers might be slightly out-of-date. Here's what worked for me with Rails 5 and ruby 2.3:



        In the form:



        <%= f.label :options %>
        <%= 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 %>


        and then in the controller I had to update the strong parameters like so:



        def widget_params
        params.require(:widget).permit(:any, :regular, :parameters, :options => [:axis_y, :axis_x, ...])
        end


        It seems to be important that the serialized hash parameter comes at the end of the list of parameters. Otherwise, Rails will expect the next parameter to also be a serialized hash.



        In the view I used some simple if/then logic to only display the hash if it is not empty and then to only display key/value pairs where the value was not nil.






        share|improve this answer
























        • This works for storing values, but when you open the edit form, you do not see the values you saved

          – Yaro Shm
          Feb 26 '18 at 19:58











        • @YaroShm It's been a while since I visited this problem. As I remember the strong parameters were a little bit tricky and updates to rails over the past year may have changed the necessary syntax. It'll probably take some careful debugging and maybe a little lucky poking to get it working. When you do, please post the trick here. It will help other developers that find this post in the future. Best of luck!

          – JDenman6
          Mar 2 '18 at 1:32














        4












        4








        4







        I've been struggling with a very similar problem. The solutions I found here were very helpful to me. Thank you @austinfromboston, @Christian-Butske, @sbzoom, and everyone else. However, I think these answers might be slightly out-of-date. Here's what worked for me with Rails 5 and ruby 2.3:



        In the form:



        <%= f.label :options %>
        <%= 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 %>


        and then in the controller I had to update the strong parameters like so:



        def widget_params
        params.require(:widget).permit(:any, :regular, :parameters, :options => [:axis_y, :axis_x, ...])
        end


        It seems to be important that the serialized hash parameter comes at the end of the list of parameters. Otherwise, Rails will expect the next parameter to also be a serialized hash.



        In the view I used some simple if/then logic to only display the hash if it is not empty and then to only display key/value pairs where the value was not nil.






        share|improve this answer













        I've been struggling with a very similar problem. The solutions I found here were very helpful to me. Thank you @austinfromboston, @Christian-Butske, @sbzoom, and everyone else. However, I think these answers might be slightly out-of-date. Here's what worked for me with Rails 5 and ruby 2.3:



        In the form:



        <%= f.label :options %>
        <%= 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 %>


        and then in the controller I had to update the strong parameters like so:



        def widget_params
        params.require(:widget).permit(:any, :regular, :parameters, :options => [:axis_y, :axis_x, ...])
        end


        It seems to be important that the serialized hash parameter comes at the end of the list of parameters. Otherwise, Rails will expect the next parameter to also be a serialized hash.



        In the view I used some simple if/then logic to only display the hash if it is not empty and then to only display key/value pairs where the value was not nil.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Aug 31 '16 at 17:05









        JDenman6JDenman6

        635




        635













        • This works for storing values, but when you open the edit form, you do not see the values you saved

          – Yaro Shm
          Feb 26 '18 at 19:58











        • @YaroShm It's been a while since I visited this problem. As I remember the strong parameters were a little bit tricky and updates to rails over the past year may have changed the necessary syntax. It'll probably take some careful debugging and maybe a little lucky poking to get it working. When you do, please post the trick here. It will help other developers that find this post in the future. Best of luck!

          – JDenman6
          Mar 2 '18 at 1:32



















        • This works for storing values, but when you open the edit form, you do not see the values you saved

          – Yaro Shm
          Feb 26 '18 at 19:58











        • @YaroShm It's been a while since I visited this problem. As I remember the strong parameters were a little bit tricky and updates to rails over the past year may have changed the necessary syntax. It'll probably take some careful debugging and maybe a little lucky poking to get it working. When you do, please post the trick here. It will help other developers that find this post in the future. Best of luck!

          – JDenman6
          Mar 2 '18 at 1:32

















        This works for storing values, but when you open the edit form, you do not see the values you saved

        – Yaro Shm
        Feb 26 '18 at 19:58





        This works for storing values, but when you open the edit form, you do not see the values you saved

        – Yaro Shm
        Feb 26 '18 at 19:58













        @YaroShm It's been a while since I visited this problem. As I remember the strong parameters were a little bit tricky and updates to rails over the past year may have changed the necessary syntax. It'll probably take some careful debugging and maybe a little lucky poking to get it working. When you do, please post the trick here. It will help other developers that find this post in the future. Best of luck!

        – JDenman6
        Mar 2 '18 at 1:32





        @YaroShm It's been a while since I visited this problem. As I remember the strong parameters were a little bit tricky and updates to rails over the past year may have changed the necessary syntax. It'll probably take some careful debugging and maybe a little lucky poking to get it working. When you do, please post the trick here. It will help other developers that find this post in the future. Best of luck!

        – JDenman6
        Mar 2 '18 at 1:32











        3














        No need setter/getters, I just defined in the model:



        serialize :content_hash, Hash


        Then in the view, I do (with simple_form, but similar with vanilla Rails):



          = f.simple_fields_for :content_hash do |chf|
        - @model_instance.content_hash.each_pair do |k,v|
        =chf.input k.to_sym, :as => :string, :input_html => {:value => v}


        My last issue is how to let the user add a new key/value pair.






        share|improve this answer
























        • Mostly worked, except I'm dealing with a deep hash and only the root level ends up as a hash with this.

          – cpuguy83
          Aug 22 '12 at 13:33
















        3














        No need setter/getters, I just defined in the model:



        serialize :content_hash, Hash


        Then in the view, I do (with simple_form, but similar with vanilla Rails):



          = f.simple_fields_for :content_hash do |chf|
        - @model_instance.content_hash.each_pair do |k,v|
        =chf.input k.to_sym, :as => :string, :input_html => {:value => v}


        My last issue is how to let the user add a new key/value pair.






        share|improve this answer
























        • Mostly worked, except I'm dealing with a deep hash and only the root level ends up as a hash with this.

          – cpuguy83
          Aug 22 '12 at 13:33














        3












        3








        3







        No need setter/getters, I just defined in the model:



        serialize :content_hash, Hash


        Then in the view, I do (with simple_form, but similar with vanilla Rails):



          = f.simple_fields_for :content_hash do |chf|
        - @model_instance.content_hash.each_pair do |k,v|
        =chf.input k.to_sym, :as => :string, :input_html => {:value => v}


        My last issue is how to let the user add a new key/value pair.






        share|improve this answer













        No need setter/getters, I just defined in the model:



        serialize :content_hash, Hash


        Then in the view, I do (with simple_form, but similar with vanilla Rails):



          = f.simple_fields_for :content_hash do |chf|
        - @model_instance.content_hash.each_pair do |k,v|
        =chf.input k.to_sym, :as => :string, :input_html => {:value => v}


        My last issue is how to let the user add a new key/value pair.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered May 7 '12 at 5:34









        gamovgamov

        2,95912524




        2,95912524













        • Mostly worked, except I'm dealing with a deep hash and only the root level ends up as a hash with this.

          – cpuguy83
          Aug 22 '12 at 13:33



















        • Mostly worked, except I'm dealing with a deep hash and only the root level ends up as a hash with this.

          – cpuguy83
          Aug 22 '12 at 13:33

















        Mostly worked, except I'm dealing with a deep hash and only the root level ends up as a hash with this.

        – cpuguy83
        Aug 22 '12 at 13:33





        Mostly worked, except I'm dealing with a deep hash and only the root level ends up as a hash with this.

        – cpuguy83
        Aug 22 '12 at 13:33











        2














        I will suggest something simple, because all the time, when user will save form You will get string. So You can use for example before filter and parse those data like that:



        before_save do
        widget.options = YAML.parse(widget.options).to_ruby
        end


        of course You should add validation if this is correct YAML.
        But it should works.






        share|improve this answer




























          2














          I will suggest something simple, because all the time, when user will save form You will get string. So You can use for example before filter and parse those data like that:



          before_save do
          widget.options = YAML.parse(widget.options).to_ruby
          end


          of course You should add validation if this is correct YAML.
          But it should works.






          share|improve this answer


























            2












            2








            2







            I will suggest something simple, because all the time, when user will save form You will get string. So You can use for example before filter and parse those data like that:



            before_save do
            widget.options = YAML.parse(widget.options).to_ruby
            end


            of course You should add validation if this is correct YAML.
            But it should works.






            share|improve this answer













            I will suggest something simple, because all the time, when user will save form You will get string. So You can use for example before filter and parse those data like that:



            before_save do
            widget.options = YAML.parse(widget.options).to_ruby
            end


            of course You should add validation if this is correct YAML.
            But it should works.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Apr 20 '12 at 22:21









            mtfkmtfk

            840612




            840612























                1














                I'm trying to do something similar and I found this sort of works:



                <%= form_for @search do |f| %>
                <%= f.fields_for :params, @search.params do |p| %>
                <%= p.select "property_id", [[ "All", 0 ]] + PropertyType.all.collect { |pt| [ pt.value, pt.id ] } %>

                <%= p.text_field :min_square_footage, :size => 10, :placeholder => "Min" %>
                <%= p.text_field :max_square_footage, :size => 10, :placeholder => "Max" %>
                <% end %>
                <% end %>


                except that the form fields aren't populated when the form is rendered. when the form is submitted the values come through just fine and i can do:



                @search = Search.new(params[:search])


                so its "half" working...






                share|improve this answer




























                  1














                  I'm trying to do something similar and I found this sort of works:



                  <%= form_for @search do |f| %>
                  <%= f.fields_for :params, @search.params do |p| %>
                  <%= p.select "property_id", [[ "All", 0 ]] + PropertyType.all.collect { |pt| [ pt.value, pt.id ] } %>

                  <%= p.text_field :min_square_footage, :size => 10, :placeholder => "Min" %>
                  <%= p.text_field :max_square_footage, :size => 10, :placeholder => "Max" %>
                  <% end %>
                  <% end %>


                  except that the form fields aren't populated when the form is rendered. when the form is submitted the values come through just fine and i can do:



                  @search = Search.new(params[:search])


                  so its "half" working...






                  share|improve this answer


























                    1












                    1








                    1







                    I'm trying to do something similar and I found this sort of works:



                    <%= form_for @search do |f| %>
                    <%= f.fields_for :params, @search.params do |p| %>
                    <%= p.select "property_id", [[ "All", 0 ]] + PropertyType.all.collect { |pt| [ pt.value, pt.id ] } %>

                    <%= p.text_field :min_square_footage, :size => 10, :placeholder => "Min" %>
                    <%= p.text_field :max_square_footage, :size => 10, :placeholder => "Max" %>
                    <% end %>
                    <% end %>


                    except that the form fields aren't populated when the form is rendered. when the form is submitted the values come through just fine and i can do:



                    @search = Search.new(params[:search])


                    so its "half" working...






                    share|improve this answer













                    I'm trying to do something similar and I found this sort of works:



                    <%= form_for @search do |f| %>
                    <%= f.fields_for :params, @search.params do |p| %>
                    <%= p.select "property_id", [[ "All", 0 ]] + PropertyType.all.collect { |pt| [ pt.value, pt.id ] } %>

                    <%= p.text_field :min_square_footage, :size => 10, :placeholder => "Min" %>
                    <%= p.text_field :max_square_footage, :size => 10, :placeholder => "Max" %>
                    <% end %>
                    <% end %>


                    except that the form fields aren't populated when the form is rendered. when the form is submitted the values come through just fine and i can do:



                    @search = Search.new(params[:search])


                    so its "half" working...







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jan 26 '11 at 6:50









                    emhemh

                    80911325




                    80911325























                        1














                        I was facing the same issue, after some research i found a solution using Rails' store_accessor to make keys of a serialized column accessible as attributes.



                        With this we can access "nested" attributes of a serialized column …



                        # post.rb
                        class Post < ApplicationRecord
                        serialize :options
                        store_accessor :options, :value1, :value2, :value3
                        end

                        # set / get values
                        post = Post.new
                        post.value1 = "foo"
                        post.value1
                        #=> "foo"
                        post.options['value1']
                        #=> "foo"

                        # strong parameters in posts_controller.rb
                        params.require(:post).permit(:value1, :value2, :value3)

                        # form.html.erb
                        <%= form_with model: @post, local: true do |f| %>
                        <%= f.label :value1 %>
                        <%= f.text_field :value1 %>
                        # …
                        <% end %>





                        share|improve this answer




























                          1














                          I was facing the same issue, after some research i found a solution using Rails' store_accessor to make keys of a serialized column accessible as attributes.



                          With this we can access "nested" attributes of a serialized column …



                          # post.rb
                          class Post < ApplicationRecord
                          serialize :options
                          store_accessor :options, :value1, :value2, :value3
                          end

                          # set / get values
                          post = Post.new
                          post.value1 = "foo"
                          post.value1
                          #=> "foo"
                          post.options['value1']
                          #=> "foo"

                          # strong parameters in posts_controller.rb
                          params.require(:post).permit(:value1, :value2, :value3)

                          # form.html.erb
                          <%= form_with model: @post, local: true do |f| %>
                          <%= f.label :value1 %>
                          <%= f.text_field :value1 %>
                          # …
                          <% end %>





                          share|improve this answer


























                            1












                            1








                            1







                            I was facing the same issue, after some research i found a solution using Rails' store_accessor to make keys of a serialized column accessible as attributes.



                            With this we can access "nested" attributes of a serialized column …



                            # post.rb
                            class Post < ApplicationRecord
                            serialize :options
                            store_accessor :options, :value1, :value2, :value3
                            end

                            # set / get values
                            post = Post.new
                            post.value1 = "foo"
                            post.value1
                            #=> "foo"
                            post.options['value1']
                            #=> "foo"

                            # strong parameters in posts_controller.rb
                            params.require(:post).permit(:value1, :value2, :value3)

                            # form.html.erb
                            <%= form_with model: @post, local: true do |f| %>
                            <%= f.label :value1 %>
                            <%= f.text_field :value1 %>
                            # …
                            <% end %>





                            share|improve this answer













                            I was facing the same issue, after some research i found a solution using Rails' store_accessor to make keys of a serialized column accessible as attributes.



                            With this we can access "nested" attributes of a serialized column …



                            # post.rb
                            class Post < ApplicationRecord
                            serialize :options
                            store_accessor :options, :value1, :value2, :value3
                            end

                            # set / get values
                            post = Post.new
                            post.value1 = "foo"
                            post.value1
                            #=> "foo"
                            post.options['value1']
                            #=> "foo"

                            # strong parameters in posts_controller.rb
                            params.require(:post).permit(:value1, :value2, :value3)

                            # form.html.erb
                            <%= form_with model: @post, local: true do |f| %>
                            <%= f.label :value1 %>
                            <%= f.text_field :value1 %>
                            # …
                            <% end %>






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 23 '18 at 14:15









                            R4ttlesnakeR4ttlesnake

                            4641619




                            4641619






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1002963%2fhow-to-edit-a-rails-serialized-field-in-a-form%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                If I really need a card on my start hand, how many mulligans make sense? [duplicate]

                                Alcedinidae

                                Can an atomic nucleus contain both particles and antiparticles? [duplicate]