【问题标题】:No Method Error Undefined method 'save' for nil:NilClass无方法错误 nil:NilClass 的未定义方法“保存”
【发布时间】:2012-06-13 11:08:49
【问题描述】:

当我尝试通过 Lecture 控制器的 create 方法创建“Lecture”时出现此错误。这曾经可以工作,但我继续在应用程序的其他部分工作,然后我当然回来了,当用户尝试在我的应用程序中创建讲座时,现在出现了这个错误。

我确定它只是我忽略的一些小东西(已经做了一段时间了,可能需要休息一下)......但如果有人能让我知道为什么会发生这种情况,我将不胜感激......如果我需要发布其他任何内容,请告诉我...谢谢!

我得到的错误

NoMethodError in LecturesController#create

undefined method `save' for nil:NilClass
Rails.root: /Users/name/Sites/rails_projects/app_name

Application Trace | Framework Trace | Full Trace
app/controllers/lectures_controller.rb:13:in `create'

我对创建新讲座的看法

观点/讲座/new.html.erb

<% provide(:title, 'Start a Lecture') %>

<div class="container">
  <div class="content-wrapper">

    <h1>Create a Lecture</h1>

     <div class="row">
       <div class="span 6 offset3">
         <%= form_for(@lecture) do |f| %>
           <%= render 'shared/error_messages', :object => f.object %>
           <div class="field">
             <%= f.text_field :title, :placeholder => "What will this Lecture be named?" %>
             <%= f.text_area :content, :placeholder => "Describe this Lecture & what will be learned..." %>
           </div>
          <%= f.submit "Create this Lecture", :class => "btn btn-large btn-primary" %>
         <% end %>
       </div>
     </div>
   </div>
 </div>

然后我的控制器说错误来自哪里

controllers/lectures_controller.rb

class LecturesController < ApplicationController
before_filter :signed_in_user, :only => [:create, :destroy]
before_filter :correct_user,   :only => :destroy

def index
end

def new
  @lecture = current_user.lectures.build if signed_in?
end

def create
  if @lecture.save
   flash[:success] = "Lecture created!"
   redirect_to @lecture
  else
   @activity_items = [ ]
   render 'new'
  end
end

def show
 @lecture = Lecture.find(params[:id])
end

def destroy
  @lecture.destroy
  redirect_to root_path
end


private

  def correct_user
    @lecture = current_user.lectures.find_by_id(params[:id])
    redirect_to root_path if @lecture.nil?
  end

【问题讨论】:

  • 没有保存方法,就像报错说的那样,到时候有讲座吗?
  • 嗨,戴夫...在用户提交该表单之前,不应存在任何讲座。但我认为我的创建方法正在处理保存???

标签: ruby-on-rails model-view-controller methods null


【解决方案1】:

您依靠 before 过滤器为后续操作设置实例变量。这行不通。您必须在需要它的控制器操作中显式设置它。 before 过滤器的唯一目的是过滤哪些操作会运行,哪些不运行。

编辑:我误读了您的代码。我以为您在创建操作之前正在运行正确的用户。无论哪种方式,很高兴知道它现在有效!

【讨论】:

  • 谢谢 cdesrosiers...你能说得更具体一点吗?在“def create”方法中的控制器中设置它?
  • 是的,当您进入创建操作时,@lecture 尚未设置。它是零。您需要先在创建中添加行@lecture = Lecture.new(params[:lecture])。这假设您正在从表单中传递数据。
  • 认为我明白了 - 看看上面的更改是否看起来更好
  • 现在可以使用 - 像往常一样感谢您的帮助......我的愚蠢错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-27
  • 2015-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-21
相关资源
最近更新 更多