尝试访问视图中的类属性时出现未定义的方法错误

时间:2016-03-10 23:40:39

标签: ruby-on-rails ruby

我有一个问题和正确的答案模型。我创建了一个表单来填写问题和正确的答案,正确的答案是嵌套属性。但是,当我想创建一个显示所有问题和答案的视图时,我无法输出相应问题的正确答案。

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 

1 个答案:

答案 0 :(得分:0)

这仅表示if中的一个或多个问题没有@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 %> 模板中引入变量也不是一个好主意。