nil:Class的未定义方法错误“错误”

时间:2014-07-26 22:50:47

标签: ruby-on-rails ruby

我的错误说它有:“未定义的方法`错误'为nil:NilClass”和“NoMethodError in Questions #index”

错误表示错误是。

<% if object.errors.any? %>
<ul id="form-errors">
    <% object.errors.full_messages.each do |message| %>
        <li><%= message %></li>

我的问题控制器,我认为错误是。

    class QuestionsController < ApplicationController
    before_filter :auth, only: [:create, :your_questions, :edit, :update]

  # def index
  #     @question = Question.new
  #   @questions = Question.unsolved(params)
  # end

  def self.unsolved(params)
    order('created_at DESC').where(solved: false).paginate(page: params[:page],per_page: 3)
  end

  def create
    @question = current_user.questions.build(params[:question])
    if @question.save
        flash[:success] = 'Your question has been posted!'
        redirect_to @question
    else
      @questions = Question.unsolved(params)
        render 'index'
    end
  end

  def new
       @question = Question.new
  end

  def show
    puts params
    @question = Question.find(params[:id])
    @answer = Answer.new
  end

  def your_questions
    @questions = current_user.your_questions(params[:id])
  end

  def edit
    @question = current_user.questions.find(params[:id])
  end

  def update
    @question = current_user.questions.find(params[:id])

    if @question.update_attributes(params[:question])
      flash[:success] = 'Your question has been updated!'
      redirect_to @question
    else
      render 'edit'
    end
  end

  def search
    @questions = Question.search(params)
  end
end

我的完整_question_form.html.erb

<%= form_for(@question) do |f| %>
<%= render 'shared/error_messages', object: f.object %>

<p>
    <%= f.label :body, "Question" %><br />
    <%= f.text_field :body %>

    <%= f.submit "Ask a Question" %>
</p>

应用/查看/ new.html.erb

 <% provide(:title, 'Make It Snappy Q&A - Register') %>

<h1>Register</h1>

<%= form_for(@user) do |f| %>
    <%= render 'common/form_errors', object: @user %>

    <p>
        <%= f.label :username %><br />
        <%= f.text_field :username %>
    </p>

    <p>
        <%= f.label :password %><br />
        <%= f.password_field :password %>
    </p>

    <p>
        <%= f.label :password_confirmation, 'Confirm' %><br />
        <%= f.password_field :password_confirmation %>
    </p>

    <p>
        <%= f.submit "Register" %>
    </p>
<% end %>

1 个答案:

答案 0 :(得分:1)

您的文件app/views/questions/edit.html.erbapp/views/questions/new.html.erb最有可能调用某些部分...我猜部分是:

app/views/questions/_form.html.erb

是吗?

在任何情况下,这部分可能在顶部有这两行...

<%= form_for(@question) do |f| %>  
    <%= render 'shared/error_messages' %>

因此,您调用_error_messages部分而不指定部分中的object应该引用的内容。所以把它改成......

<%= form_for(@question) do |f| %>  
    <%= render 'shared/error_messages', object: @question %>

或者,你可以......

<%= form_for(@question) do |f| %>  
    <%= render 'shared/error_messages', object: f.object %>

哪个完全相同,但稍微更好,因为表单只需要提一次实例变量。