0
votes

So I have a doubly nested associations like Foos having many Bars that have many Bazs. The Baz model has a serialized field called data that takes the form of a hash that maps ranges (i.e: 1..3) to a numerical value. { (1..3) => 42 }

Currently in the Active Admin edit page I have something like:

form do |f|
    f.semantic_errors
    f.has_many :bars, heading "Bar" do |t|
        f.input :item_one
        f.input :item_two
        t.has_many :bazs do |r|
            r.input :name
            r.input :data, as: :string
        end
    end
end

As you can see I am dealing with the Hash as a string, and rendering it in a text box in the edit page. I'd like to be able to loop over the already existing data and render them into separate text boxes so they can be edited indidividually or deleted... But on submitting the form it would glue together these inputs and pass the data as a hash rather than a string.

Can this be done by writing a custom form builder? What is the best approach?

I'd like to build an extensible solution that doesn't require any code to be written into the model or controllers.

Thank for reading o//

Update: I found a solution that works for me. Since the whole problem here was that our data was serialized from Hash into string when being placed into database, it made sense to allow the user to edit this data as JSON and make changes to the setter method on model that takes the data to allow it to parse the JSON. This made things simpler as I could just use this JSON editor widget to give a nice UI to edit the data with. The trick was then to learn how to apply the widget to items created with the "Add New Item" button. Looking at the active admin source code I learned that I could hook into the has_many_add:after event to apply the JSON editor to the added element after it had already been added to the DOM tree.

1
I would typically do this by adding a virtual attribute to the model. How strongly do you feel about keeping code in helpers and views? - moveson

1 Answers

0
votes

I would try and hide the transformation from the form using a decorator. Otherwise hstore editor might give you some inspiration. I would recommend against a custom form builder, especially with nested has_many.