I'm using Rails 4.1.4 on a Xubuntu machine. I have a Question model that has many alternativas (possible answers in my language), like this:
# question.rb
class Question < ActiveRecord::Base
has_many :alternativas, dependent: :destroy
validates_presence_of :text
accepts_nested_attributes_for :alternativas, reject_if: proc {|attributes| attributes[:texto].blank? }
end
# alternativa.rb
class Alternativa < ActiveRecord::Base
belongs_to :question
end
Question only has the :text attribute (string), and answer only the :texto attribute (also a string). I can create a question, but when I try to edit it, it edits only the question text, not the answers. New answers are created instead of the old ones being updated.
Also, as the :text field is required, when I leave it blank it redirects to the same page with the error message, but for some weird reason all the answers are doubled (if there is one answer when I submit the form, there will be 2 equal answers when it shows the error message).
So how can I solve this two problems? My guess is that I'm not using the build and the accepts_nested_attributes_for methods correctly, so here is my controller:
class QuestionsController < ApplicationController
before_action :set_question, only: [:show, :edit, :update, :destroy]
before_filter :authorize
before_filter :verify_admin
def index
@questions = Question.all
end
def show
end
def new
@question = Question.new
@question.alternativas.build # I also tried 5.times { @question.alternativas.build } for 5 answers text fields
end
def edit
end
def create
@question = Question.new(question_params)
respond_to do |format|
if @question.save
format.html { redirect_to @question, notice: 'Question was successfully created.' }
format.json { render :show, status: :created, location: @question }
else
format.html { render :new }
format.json { render json: @question.errors, status: :unprocessable_entity }
end
end
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
def destroy
@question.destroy
respond_to do |format|
format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_question
@question = Question.find(params[:id])
end
def question_params
params.require(:question).permit(:text, { alternativas_attributes: [:texto, :question_id] })
end
end