'Can you refresh a nested object with JS so the attributes that depend on parent attributes are reloaded as well?

I have a Plan model which has_many Versions. I'm nesting a Version form inside a Plan form.

form

<%= simple_form_for @plan do |f| %>
  <%= f.simple_fields_for :version do |v| %>
    <%= v.input :amount, hint: "#{pricing_model_hint_for_amount(@version)}" %>
  <% end %>
<% end %>

I build the Version in the PlansController #new action:

controller action

  def new
    @plan = current_account.plans.build
    @version = @plan.versions.build
  end

Now for example, the @version hint for the amount input depends on an attribute of it's parent Plan called :pricing_model. The input's hint attribute consumes a helper that will will look at the @version.plan.pricing_model to fetch the right hint from a YAML file.

helper

  def pricing_model_hint_for_amount(version)
    t("simple_form.hints.version.pricing_model.#{version.plan.pricing_model}")
  end

Problem:

Because @version is instantiated when the form is loaded, the hint is not updated dynamically when I change the @plan pricing_model in the form.

Is there a way (with or without Javascript) to reload the nested @plan so the form hints are updated accordingly if something in it's parent changes? If not, is there a way to reload the hint field itself so when the helper is consumed again the same result is achieved?

I hope I explained myself, otherwise please let me know. Thanks.



Solution 1:[1]

What version of rails are you on?

If you are on rails 7 you should look into using either:

a stimulus controller to listen on the changes and update your tooltip. (more js)

How to create a controller, and the action you can listen to.

or:

a turbo-frame to reload parts of your form on demand. (more ruby)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 felunka