2016-03-10 40 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 %>' –