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


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:


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


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

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

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


class QuestionsController < ApplicationController
    before_action :set_question, only: [:show, :edit, :update, :destroy]
    before_action :authenticate_user!, except: [:show, :index]
    def edit
    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 }
                format.html { render :edit }
                format.json { render json: @question.errors, status: :unprocessable_entity }

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

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

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 70,078+ 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.

    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.