0

I have a model for Experiment and the schema looks like this:

create_table "experiments", id: :serial, force: :cascade do |t|
    t.string "name"
    t.string "state"
    t.jsonb "experiment_conditions"
end

As you can see in the schema, experiment_conditions is type jsonb. I want the user to be able to name the key whatever they want and give it a number (percentage of 100).

For example: {"control": 10, "variant": 90} or {"control": 50, "other": 50}

The issue I am having is with the form in the view file. I know that I need it to follow this pattern:

<%= form.text_field_tag "experiment[experiment_conditions][name_of_key]", [experiment_value] %>

But I can't figure out a way to allow the user to enter both the key and value of a nested object in a rails form. I've considered using the cocoon gem, but from the looks of it, that gem only works with ActiveRecord associated models. Anyhow, thank you in advance!

Note: I'm hoping to find a solution without using javascript

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Steez
  • 219
  • 5
  • 17
  • Does the user have to be able to create several of these keys at once? – max Jan 06 '20 at 21:58
  • Yes. They need to have at least 2 variants ["Control", "Variant"] or ["Control", "a", "b"] – Steez Jan 06 '20 at 23:03
  • Are you really that married to the idea of a JSON column? This sounds like something you could do by adding a separate experiment_conditions table with a has_many association and `accepts_nested_attributes_for :experiment_conditions` – max Jan 06 '20 at 23:17
  • @max I was thinking the same thing. It was actually the existing data structure on something I was working on. Might have no choice but to break it up into separate tables – Steez Jan 06 '20 at 23:19
  • Breaking it up on the whole is probably positive as it gives you some sort of schema. – max Jan 06 '20 at 23:26

0 Answers0