未定义的方法`回答'上课

时间:2015-03-28 16:43:29

标签: ruby-on-rails ruby ruby-on-rails-4

我有表格,我可以提问,并在这个问题上添加几个答案 当我尝试保存我的问题和答案时点击“创建”我收到错误:

"undefined method `answer'" in questions_controller.rb in 'create' method.

我的问题.rb模型:

class Question < ActiveRecord::Base
  has_many :answers, :dependent => :destroy

  accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true

  before_save { self.content = content.downcase }
  validates :content, presence: true, length: { maximum: 150 }
end

我的回答.rb模型:

class Answer < ActiveRecord::Base
  belongs_to :question

  validates :answer, presence: true, length: { maximum: 150 }
end

questions_controller.rb:

class QuestionsController < ApplicationController
  def show
    @question = Question.find(params[:id])
  end

  def new
    @question = Question.new
    3.times do
      answer = @question.answers.build
    end
  end

  def create
    @question = Question.new(question_params)
    if @question.save
      flash[:success] = "Welcome to the Sample App!"
      redirect_to @question
    else
      render 'new'
    end
  end

  private
    def question_params
      params.require(:question).permit(:content, answers_attributes: [:content])
    end
end

并查看new.html.erb:

<div class="row center-block">
  <div class="col-md-2 col-md-offset-3">
    <%= form_for @question do |f| %>
        <%= render 'shared/error_messages' %>

        <%= f.label :content %>
        <%= f.text_field :content %>

        <%= f.fields_for :answers do |builder| %>
            <%= render "answer_fields", :f => builder %>
        <% end %>

        <div class="center hero-unit">
            <%= f.submit "Create Poll", class: "btn btn-large btn-primary" %>
        </div>
    <% end %>
  </div>
</div>

并渲染了answer_fields:

<p>
  <%= f.label :content %><br>
  <%= f.text_area :content, :rows => 3 %><br>
  <%= f.check_box :_destroy %>
  <%= f.label :_destroy, "Remove answer"%>
</p>

1 个答案:

答案 0 :(得分:1)

在没有堆栈跟踪的情况下很难跟踪问题,但是在我的表单中有什么让我怀疑的是,contentAnswer字段:

<%= f.text_area :content, :rows => 3 %>

这已在您的控制器中正确处理(再次 - 您允许:content answers_attributes

params.require(:question).permit(:content, answers_attributes: [:content])

但您在Answer字段:answer上进行了验证:

validates :answer, presence: true, length: { maximum: 150 }

尝试将其更改为

validates :content, presence: true, length: { maximum: 150 }

希望有所帮助!