[英]Rails undefined method * for nil:NilClass
我遇到了一個問題,並且進行了一些研究,從研究中我發現所使用的變量為空,但是我不確定為什么它為空,也許對其他人很明顯?
我試圖在另一個控制器的頁面上顯示嵌套表單,我使用的是嵌套資源,我認為這可能是我的問題,但不確定如何解決。
出現以下錯誤:
undefined method `submission' for nil:NilClass
項目主文件夾的結構-成員-問題-提交
概念:
問題-has_many-提交內容-屬於-問題
提交模型:
class Submission < ActiveRecord::Base
belongs_to :question
belongs_to :member
end
問題模型:
class Members::Question < ActiveRecord::Base
has_many :submissions
end
提交負責人:
def create
@question = Members::Question.find(params[:question_id])
@submission.member_id = current_member.id
@submission = @question.submissions.create(params[:submission].permit(:content, :question_id))
*Redirect Method Here *
end
在表單中,我使用以下方法:
<%= form_for([@question, @question.submission.build]) do |f| %>
<% if @submission.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@submission.errors.count, "error") %> prohibited this submission from being saved:</h2>
<ul>
<% @submission.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :content %><br>
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
然后在問題的顯示頁面上顯示表單,我正在使用
<%= render 'members/submissions/form' %>
路線:
namespace :members do
resources :questions, only: [:index,:show] do
resources :submissions
end
end
任何人有任何想法我要去哪里錯嗎?
任何幫助表示贊賞。
我已經解決了問題,謝謝您的建議,我使用的是錯誤的變量,我使用的是@question,由於嵌套,正確的變量是@members_question
提交控制器
def create
@members_question = Members::Question.find(params[:question_id])
@submission = @members_question.submissions.create(params[:submission].permit(:content, :question_id))
@submission.member_id = current_member.id
end
_form.html.erb
<%= form_for([@members_question, @members_question.submissions.build]) do |f| %>
<div class="field">
<%= f.label :content %><br>
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.