All threads / Rails - adding nested attributes then validation fails, new nested attributes are not passed back to the :edit render

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Rails - adding nested attributes then validation fails, new nested attributes are not passed back to the :edit render

Dan Tappin asked in Rails

I have a Rails app with nested attributes. My MVC works great except when the nested validation fails. Here is my parent model controller:

    def update

        if @model.update(model_params)

            respond_to do |format|
                format.html { redirect_to @model, notice: 'Model was successfully updated.'}
            end

        else
            render :edit
        end
    end

The issue is then in my model view when I build the nested form again:

<%= f.simple_fields_for :nested_model, @model.nested_model.joins(:related_model).order(:name)  do |i| %>

I get all the original nested_model items in the form but the new ones that were passed in the params are not added. This works 100% when there are no validation issues. How do I add those invalid nested_model items back in here. I feel like there is an existing solution to this that I can't seem to find easily.

Eliminating the @model.nested_model.joins(:related_model).order(:name) did the trick.

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 33,399+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.