2016-03-10 48 views
0

类属性时,我有一个问题,正确答案的模式。我创建了一个表单来填写问题和正确答案,正确答案是嵌套属性。但是,当我想创建一个显示所有问题和答案的视图时,我无法为相应的问题输出正确的答案。未定义的方法错误试图访问鉴于

class Question < ActiveRecord::Base 
    has_one :correct_answer 
    accepts_nested_attributes_for :correct_answer 
end 

class CorrectAnswer < ActiveRecord::Base 
    belongs_to :Question 
end 

create_table "questions", force: true do |t| 
    t.string "title" 
    end 

create_table "correct_answer", force: true do |t| 
    t.integer "question_id" 
    t.string "solution" 
    end 

<%= form_for @question, url: question_path do |f| %> 
<%= f.text_field :title %> 
<%= f.fields_for :correct_answer do |q| %> 
    <%= q.text_field :solution %> 
<% end %> 
<% end %> 

questions_controller:

def show 
     @q = Question.all 
    end 

    def new 
     @question = Question.new 
     @question.build_correct_answer 
    end 

    def create 
     @question = Question.new(question_params) 

     if @question.save 
      redirect_to action: "show" 
     else 
      render action: :new 
     end 
    end 

    private 
    def question_params 

     params.require(:question).permit(:title, correct_answer_attributes: [:solution]) 
    end 
end 

show.html.erb:

<% @q.each do |question| %> 
<%= question.title %><br /> 
<% @answer = question.correct_answer %><br /> 
<%= @answer.solution %> 
<%end %> 

渲染

<% @answer = question.correct_answer %> 

#<CorrectAnswer:0x7d68aa0> 

这是一类正确答案的对象,但我得到

undefined method `solution' for nil:NilClass error 

回答

0

这只是意味着一个或多个您的问题从@q没有correct_answer。您可以轻松地检查它是这样的:

<% @q.each do |question| %> 
    <%= question.title %><br /> 
    <% if question.correct_answer.nil? %> 
    This question doesn't have a correct answer. 
    <% else %> 
    <% @answer = question.correct_answer %><br /> 
    <%= @answer.solution %> 
    <% end %> 
<% end %> 

它也没有引入erb模板中的变量是一个好主意。

+0

能否请你建议理想的方式做到这一点 –

+0

你的意思是摆脱变量赋值?你可以像这样'question.correct_answer.try(:solution)'输出它。或者更好,为了遵循[Demeter法](https://en.wikipedia.org/wiki/Law_of_Demeter),在'Question'模型中引入'solution'方法:'def solution; correct_answer.try(:溶液);结束“并在您的模板中调用它:'<%@ q.each do | question | %><%= question.title%><%= question.solution%><% end %>' –