0
我正在嘗試創建一個基本調查應用程序。我試圖用用戶創建的任何答案來創建一個選擇,但出於某種原因,我的問題沒有在我的選擇控制器中設置。Rails params問題
這裏是我的路線:
resources :questions do
resources :choices, only: [:create, :destroy]
end
我的觀點:
<h3>Questions:</h3>
<ul><% @survey.questions.each do |question| %>
<li><p><%= question.title %></p></li>
<% choice = question.choices.build %>
<% if question.single_response == true %>
<%= form_for [question, choice] do |f| %>
<% question.answers.each do |answer| %>
<%= f.radio_button :answer_id, answer.id %> <%= answer.title %><br>
<% end %>
<%= f.hidden_field :survey_id, value: @survey.id %>
<%= f.submit %>
在我的選擇控制器我set_question方法:
def set_question
@question = Question.find(params[:question_id])
end
,然後我的創建方法:
def create
@choice = @question.choices.build(choice_params)
respond_to do |format|
if @choice.save
format.html { redirect_to surveys_path, notice: 'Choice was successfully created.' }
format.json { render action: 'show', status: :created, location: @choice }
else
format.html { render action: 'new' }
format.json { render json: @choice.errors, status: :unprocessable_entity }
end
end
end
這是網絡零類錯誤。
undefined method `choices' for nil:NilClass
Rails.root: /Users/thomashammond89/SurveyMe
Application Trace | Framework Trace | Full Trace
app/controllers/choices_controller.rb:27:in `create'
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"XjNNShH6jvTAcz1NQqSBU+a+2exP2STPFnja+yfbinY=",
"choice"=>{"answer_id"=>"19",
"survey_id"=>"1",
"question_id"=>"13"},
"commit"=>"Create Choice",
"question_id"=>"13"}
在我看來question_id在參數中有。任何想法爲什麼它沒有被設置?
這樣做。你知道我的before_action爲什麼不起作用嗎?也許我只是不理解某些東西,但這就是我以前總是設置實例變量的方式。 –
看看params散列的結構。你正在調用'Question.find(params [:question_id])',而'':question_id'這個鍵在'params [:choice] [:question_id]'裏面。 –
明白了。感謝您的幫助人 –