[英]Undefined method for '[]' for nil:NilClass in Rails
I am trying to validate answer for question model with options .
我试图用options验证question模型的答案。 I have a link_to check_answer method for every question.
对于每个问题,我都有一个link_to check_answer方法。 The problem is the question object is not passed to the method.
问题是问题对象没有传递给方法。 On the same page I have link_to edit method where the question object is passed.
在同一页面上,我具有link_to edit方法,其中传递了问题对象。 Even the url on the link_to check_answer shows the correct url.
甚至link_to check_answer上的网址也会显示正确的网址。 Where is the mistake here?
这里的错误在哪里?
show.html.erb
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 %>
Here the link_to Edit passes the @question object to the controller but not the link_to Check Answer .
在这里, link_to Edit将@question对象传递给controller而不是link_to Check Answer传递给controller 。
controller.rb
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
routes.rb
Rails.application.routes.draw do
resources :questions do
member do
get 'check_answer'
end
end
end
error stack
错误堆栈
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'
error
错误
您需要在调用check_answer操作之前填充@question实例变量,为此您可以使用before_action
before_action :set_question, only: [:show, :edit, :update, :destroy, :check_answer]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.