我一直跟着兩個老的和修訂railscasts & this的東西,我必須沿着相同的路線使樓調查5
我跟着它高達一些點,但也不是所顯示的問題在表單上也沒有增加答案。以下是我的模型代碼
answers.rb
class Answer < ActiveRecord::Base
attr_accessor :content, :question_id
belongs_to :question
end
surveys.rb
class Survey < ApplicationRecord
attr_accessor :name, :questions_attributes
has_many :questions
accepts_nested_attributes_for :questions, allow_destroy: true
end
questions.rb
class Question < ApplicationRecord
attr_accessor :content, :survey_id, :answers_attributes
belongs_to :survey
has_many :answers
accepts_nested_attributes_for :answers, allow_destroy: true
end
調查控制器
class SurveysController < ApplicationController
before_action :set_survey, only: [:show, :edit, :update, :destroy]
# GET /surveys
# GET /surveys.json
def index
@surveys = Survey.all
end
# GET /surveys/1
# GET /surveys/1.json
def show
end
# GET /surveys/new
def new
@survey = Survey.new
3.times do
question = @survey.questions.build
4.times { question.answers.build }
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, :question_id)
end
end
瀏覽
_form.html.erb
<%= f.fields_for :questions do |builder| %>
<%= render 'question_fields', f: builder %>
<% end %>
<%= link_to_add_fields "Add Question", f, :questions %>
_question_fields.html.erb
<fieldset>
<%= f.label :content, "Question" %><br />
<%= f.text_area :content %><br />
<%= f.check_box :_destroy %>
<%= f.label :_destroy, "Remove Question" %>
<%= f.fields_for :answers do |builder| %>
<%= render 'answer_fields', f: builder %>
<% end %>
<%= link_to_add_fields "Add Answer", f, :answers %>
</fieldset>
_answers_fields.html.erb
<p>
<%= f.label :content, "Answer" %>
<%= f.text_field :content %>
<%= f.check_box :_destroy %>
<%= f.label :_destroy, "Remove" %>
</p>
show.html.erb
<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>
<p>
<%= link_to "Edit", edit_survey_path(@survey) %> |
<%= link_to "Destroy", @survey, :confirm => 'Are you sure?', :method => :delete %> |
<%= link_to "View All", surveys_path %>
</p>
遷移
class CreateSurveys < ActiveRecord::Migration[5.0]
def change
create_table :surveys do |t|
t.string :name
t.timestamps
end
end
end
class CreateQuestions < ActiveRecord::Migration[5.0]
def change
create_table :questions do |t|
t.string :survey_id
t.string :integer
t.text :content
t.timestamps
end
end
end
還有什麼我缺少的是需要不要在軌道5,我已經在這個小時,它仍然困惑我爲什麼它告訴我這個錯誤 - 表'app.answers'不存在當我從嵌套形式調用答案。任何在這方面的幫助將非常感激。
您可以發佈您的調查視圖表單嗎?它看起來像你可能期待nested_attributes,但你沒有在你的'permit'調用中將它們白名單列出,所以想要仔細檢查你的表單是否設置正確 –
主要問題出現在調查控制器的新方法中,這個特定行 - 4times {question.answers.build} –
哦,所以你甚至沒有看到,好吧...你有運行遷移和一切,對嗎? –