[英]Undefined method for '[]' for nil:NilClass in Rails
我试图用options
验证question
模型的答案。 对于每个问题,我都有一个link_to
check_answer
方法。 问题是问题对象没有传递给方法。 在同一页面上,我具有link_to
edit
方法,其中传递了问题对象。 甚至link_to
check_answer
上的网址也会显示正确的网址。 这里的错误在哪里?
show.html.erb
<p>
<strong>Body:</strong>
<%= @question.body %>
</p>
<p>
<strong>Option:</strong>
<% @question.options.each do |p| %>
<%= radio_button_tag('option',p.id) %>
<%= p.body %>
<% end %>
</p>
<p><%= link_to 'Check Answer', check_answer_question_path(@question) %></p>
<p>
<strong>User:</strong>
<%= @question.user.email %>
</p>
<%= link_to 'Edit', edit_question_path(@question) %> |
<%= link_to 'Back', questions_path %>
在这里, link_to
Edit
将@question
对象传递给controller
而不是link_to
Check Answer
传递给controller
。
controller.rb
def check_answer
puts(@question.id)
end
private
# Use callbacks to share common setup or constraints between actions.
def set_question
@question = Question.find(params[:id])
end
routes.rb
Rails.application.routes.draw do
resources :questions do
member do
get 'check_answer'
end
end
end
错误堆栈
Started GET "/questions/22/check_answer" for 127.0.0.1 at 2019-05-04 19:51:17 +0530
Processing by QuestionsController#check_answer as HTML
Parameters: {"id"=>"22"}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ /home/laxmanrm/.rvm/gems/ruby-2.6.0/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
------------------------------------check_answer------------------------------------------
Completed 500 Internal Server Error in 5ms (ActiveRecord: 0.4ms)
NoMethodError (undefined method `id' for nil:NilClass):
app/controllers/questions_controller.rb:72:in `check_answer'
错误
您需要在调用check_answer操作之前填充@question实例变量,为此您可以使用before_action
before_action :set_question, only: [:show, :edit, :update, :destroy, :check_answer]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.