类的未定义方法"答案"



我有一个表格,可以在其中提出问题,并为该问题添加几个答案
当我试图保存我的问题和答案点击"创建"我得到错误:

"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>

如果没有堆栈跟踪,很难跟踪问题,但让我怀疑的是在您的表单中,您有Answer:的字段content

<%= 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 }

希望能有所帮助!

相关内容

最新更新