Update and limit the number of nested attributes in Ruby on 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!