Attualmente sto provando a creare un modulo per un modello, che ha un numero dinamico di modelli annidati. Sto usando Nested Forms (come descritto in RailsCasts 197). Per rendere le cose ancora più complicate, ciascuno dei miei modelli nidificati ha un'associazione has_one
con un terzo modello, che vorrei anche aggiungere al modulo.has_many nested form con un modulo nidificato has_one al suo interno
Per chi si interroga sulla normalizzazione o su un approccio improprio, questo esempio è una versione semplificata del problema che sto affrontando. In realtà, le cose sono leggermente più complesse e questo è l'approccio che abbiamo deciso di adottare.
Alcuni codice di esempio per illustrare il problema di seguito:
#MODELS
class Test
attr_accessible :test_name, :test_description, :questions_attributes
has_many :questions
accepts_nested_attributes_for :questions
end
class Question
attr_accessible :question, :answer_attributes
belongs_to :test
has_one :answer
accepts_nested_attributes_for :answer
end
class Answer
attr_accessible :answer
belongs_to :question
end
#CONTROLLER
class TestsController < ApplicationController
#GET /tests/new
def new
@test = Test.new
@questions = @test.questions.build
@answers = @questions.build_answer
end
end
#VIEW
<%= form_for @test do |f| %>
<%= f.label :test_name %>
<%= f.text_box :test_name %>
<%= f.label :test_description %>
<%= f.text_area :test_description %>
<%= f.fields_for :questions do |questions_builder| %>
<%= questions_builder.label :question %>
<%= questions_builder.text_box :question %>
<%= questions_builder.fields_for :answer do |answers_builder| %>
<%= answers_builder.label :answer %>
<%= answers_builder.text_box :answer %>
<% end %>
<% end %>
<%= link_to_add_fields 'New', f, :questions %>
<% end %>
Questo codice di esempio funziona perfettamente per la prima istanza di domanda. Il problema si verifica quando un'altra domanda viene aggiunta dinamicamente per essere creata; i campi di risposta non sono visualizzati. Credo che questo sia perché sono costruiti solo per la prima domanda nel controller. C'è un modo per ottenere questo usando nested_attributes?
Per le persone che inciampano in questa domanda: considera l'utilizzo della gemma nested_form da ryanb. Ti fornirà stupendi link_to_add e link_to_remove view helper. –