I am trying to create a nested form with form_forand fields_for. After much research and success, no longer working on my project. I'm just trying to recreate railscast to see what I did wrong.
I am trying to recreate the example found at http://railscasts.com/episodes/196-nested-model-form-part-1 , which should not be so complicated as there is code, but I am unable to create the questions from the survey. Here is my code so far:
rails new surveysays
rails g scaffold survey name:string
rake db:migrate
rails g scaffold question survey_id:integer content:text
rake db:migrate
I am trying to make a video in the same sequence. My question model is:
class Question < ActiveRecord::Base
belongs_to :survey
end
My survey model:
class Survey < ActiveRecord::Base
has_many :questions, dependent: :destroy
accepts_nested_attributes_for :questions
end
My survey form with fields of nested questions:
<%= form_for(@survey) do |f| %>
...
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<%= f.fields_for :questions do |builder| %>
<p>
<%= builder.label :content, "Question" %><br/>
<%= builder.text_area :content, :row => 3 %>
</p>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
My poll shows:
<p id="notice"><%= notice %></p>
<p>
<strong>Name:</strong>
<%= @survey.name %>
</p>
<ol>
<% for question in @survey.questions %>
<li><%=h question.content%></li>
<% end %>
</ol>
<%= link_to 'Edit', edit_survey_path(@survey) %> |
<%= link_to 'Back', surveys_path %>
And my SurveysController:
class SurveysController < ApplicationController
...
def new
@survey = Survey.new
3.times { @survey.questions.build }
end
...
def create
@survey = Survey.new(survey_params)
respond_to do |format|
if @survey.save
format.html { redirect_to @survey, notice: 'Survey was successfully created.' }
format.json { render :show, status: :created, location: @survey }
else
format.html { render :new }
format.json { render json: @survey.errors, status: :unprocessable_entity }
end
end
end
...
private
def set_survey
@survey = Survey.find(params[:id])
end
def survey_params
params.require(:survey).permit(:name)
end
end
5:34, , , , , , create :
(Rails 4.1.6) 2.1.3: 001 > s = Survey.all (3,0 ) "". * "" = > #] > 2.1.3: 002 > q = s [0]. (0,6 ) "" . * "" "" . "Survey_id" =? [[ "survey_id", 2]] = > #
. SurveysController - :
_: [: id,: content] survey_params
@survey.questions.create(survey_params [: questions_attributes]) , survey.save , , : nill
. , , ?
- , .