Пытаюсь сделать вложенную форму с form_for
и fields_for
. После долгих исследований и неудач, я больше не работаю над своим проектом. Я просто пытаюсь воссоздать Railscast, чтобы посмотреть, что я сделал не так.
Я пытаюсь воссоздать пример, найденный на http://railscasts.com/episodes/196-nested-model-form-part-1, который не должен быть таким сложным, так как код есть, но я не могу создавать вопросы из опроса. Вот мой код до сих пор:
rails new surveysays
rails g scaffold survey name:string
rake db:migrate
rails g scaffold question survey_id:integer content:text
rake db:migrate
Я пытаюсь сделать в той же последовательности ролика. Моя модель вопроса:
class Question < ActiveRecord::Base
belongs_to :survey
end
Моя модель опроса:
class Survey < ActiveRecord::Base
has_many :questions, dependent: :destroy
accepts_nested_attributes_for :questions
end
Моя форма опроса с полями вложенных вопросов:
<%= 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 %>
Мой опрос показывает:
<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 %>
И мой SurveysController:
class SurveysController < ApplicationController
...
# GET /surveys/new
def new
@survey = Survey.new
3.times { @survey.questions.build }
end
...
# POST /surveys
# POST /surveys.json
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
# Use callbacks to share common setup or constraints between actions.
def set_survey
@survey = Survey.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def survey_params
params.require(:survey).permit(:name)
end
end
До мин. 5:34, когда он не работает, как показано в видео, и не создает вопросов, появляется форма с тремя вопросами, я заполняю форму, но когда нажимаю create kbd> это не создает вопросов:
Загрузка среды разработки (Rails 4.1.6) 2.1.3: 001> s = Survey.all Survey Load (3,0 мс) ВЫБРАТЬ «Опросы». * FROM «Survey» => #]> 2.1.3: 002> q = s [0] .questions Загрузка вопросов (0,6 мс) ВЫБЕРИТЕ "questions". * FROM "questions" ГДЕ "questions". "Survey_id" =? [["survey_id", 2]] => #
Я не вижу разницы между моим кодом и примером. Я даже безуспешно пытался внести некоторые изменения в SurveysController
:
Вставка question_attributes: [: id,: content] в разрешении метода survey_params или Inserting @ survey.questions.create (survey_params [: questions_attributes]) после if survey.save в методе create, это создает вопрос, но с content: nill
На этом я застрял. Я не знаю, что еще делать, что мне не хватает в контроллере? Кто-нибудь может мне помочь, спасибо.