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.

Reply

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

Reply
Join the discussion

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

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

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

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2023 GoRails, LLC. All rights reserved.