All threads / Update and limit the number of nested attributes in Ruby on Rails

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Update and limit the number of nested attributes in Ruby on Rails

user001 asked in Rails

I have a Question model related to Option model. Whenever I try to update question and related options, new options are created instead of updating an existing option. Why is it happening like this? Also I would like to display only four options in the form, no less no more. How can I implement it in my form?

My code is as below:

Models

class Question < ApplicationRecord
    has_many :options, dependent: :delete_all, :autosave => true
    validates_length_of :options, maximum: 4
    accepts_nested_attributes_for :options
end
class Option < ApplicationRecord
    belongs_to :question
    validates_associated :question
end

_form.html.erb

<%= form_with(model: question, local: true) do |form| %>
    <div class="field">
        <%= form.label :body %>
        <%= form.text_area :body %>
    </div>

    <%= form.fields_for :options do |a| %>
        <div class="field">
            <%= a.label :options %>
            <%= a.text_area :body %>
        </div>
   <% end %>


   <div class="actions">
       <%= form.submit %>
  </div>
<% end %>

controller

class QuestionsController < ApplicationController
    before_action :set_question, only: [:show, :edit, :update, :destroy]
    before_action :authenticate_user!, except: [:show, :index]
    def edit
    end
    def update
        respond_to do |format|
            if @question.update(question_params)
                format.html { redirect_to @question, notice: 'Question was successfully updated.' }
                format.json { render :show, status: :ok, location: @question }
            else
                format.html { render :edit }
                format.json { render json: @question.errors, status: :unprocessable_entity }
            end
        end
    end

    private 
        def set_question  
            @question = Question.find(params[:id])
        end

        def question_params
            params.require(:question).permit(:body, options_attributes: [:body])
        end
end

I have used scaffold for questions. Thanks in advance!

My first guess would be you are missing the id for your Option model—so it doesn't know which Option record to update.

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.